Spring Boot series: Spring Boot integrates Spring Cache

Keywords: Java Spring SpringBoot Database github

I. about Spring Cache

Caching is becoming more and more important in today's applications.
Spring has defined org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces since 3.1 to unify different caching technologies, and supports the use of JCache (JSR-107) annotations to simplify our development.

Through spring Cache, you can quickly embed your own Cache implementation, mainly through @ Cacheable, @ CachePut, @ CacheEvict, @ CacheConfig, @ Caching and other annotations.

  • @Cacheable: used to cache the return results of a method. If the cache already exists, it is obtained directly from the cache. The key of the cache can be specified from the input parameter. The value of the cache is the return value of the method.
  • @CachePut: used for methods. No matter whether the cache exists or not, the cache will be added again every time. The key of the cache can be specified from the input parameter. The value of the cache is the return value of the method, which is often used for updating.
  • @CacheEvict: acts on methods to clear the cache.
  • @CacheConfig: used to uniformly configure the properties of cache annotations of this class.
  • @Caching: used on methods to set multiple caches at once.
  • @EnableCaching: used on a class to enable annotation.

II. Demonstration examples

To use Spring Cache, you need to first introduce the dependency of Spring Cache.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Spring Cache rely on-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Then on the startup class, we need to use @ EnableCaching to declare open caching.

@EnableCaching //Open cache
@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

In this way, you can use annotations to operate the cache, and create a CacheService class, where the Map of dataMap stores data, eliminating the operation of the database.

@Slf4j
@Service
public class CacheService {

    private Map<Integer, User> dataMap = new HashMap <Integer, User>(){
        {
            for (int i = 1; i < 100 ; i++) {
                User u = new User("code" + i, "name" + i);
                put(i, u);
            }
        }
     };

    // get data
    @Cacheable(value = "cache", key = "'user:' + #id")
    public User get(int id){
        log.info("adopt id{}Query acquisition", id);
        return dataMap.get(id);
    }

    // Update data
    @CachePut(value = "cache", key = "'user:' + #id")
    public User set(int id, User u){
        log.info("To update id{}data", id);
        dataMap.put(id, u);
        return u;
     }
     
    //Delete data
    @CacheEvict(value = "cache", key = "'user:' + #id")
    public User del(int id){
        log.info("delete id{}data", id);
        dataMap.remove(id);
        return u;
    }

}

get method simulates query, @ Cacheable is used to add cache, set method is used to modify, @ CachePut updates cache, del method is used to delete data, @ CacheEvict deletes cache. Note that the value of the annotation represents the cache classification, not the cached object value.

Then create the CacheApi to call CacheService for testing.

@RestController
@RequestMapping("cache")
public class CacheApi {

    @Autowired
    private CacheService cacheService;

    @GetMapping("get")
    public User  get(@RequestParam int id){
        return cacheService.get(id);
    }

    @PostMapping("set")
    public User  set(@RequestParam int id, @RequestParam String code, @RequestParam String name){
        User u = new User(code, name);
        return cacheService.set(id, u);
    }

    @DeleteMapping("del")
    public void  del(@RequestParam int id){
        cacheService.del(id);
    }

}

Then we open the swagger UI interface (http: / / localhost: 10900 / swagger UI. HTML) for testing. We call the query several times. We can see that the get method of CacheService is only executed once for the same id. Then we call update again. When we get again, we can find that the data has been updated. When we call del, we can clear the cache, and when we query again, we will call the method.

Source address: https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache

Posted by elfyn on Tue, 22 Oct 2019 13:26:51 -0700