• Spring-Boot——Cache


    简单使用

    1. maven 依赖

    2. 开启缓存配置

    在启动类上开启缓存 @EnableCaching

    3. 使用缓存

    @Cacheable 是将方法的返回值保存到缓存中
    @CachePut 是根据key更新缓存中的数据
    @CacheEvict 是根据key删除缓存数据

    @Cacheable(cacheNames = {"emp"}, key = "#id")
    public Employee getEmp(Integer id) {
        Employee employeeId = employeeMapper.getEmployeeId(id);
        return employeeId;
    }
    @CachePut(cacheNames = {"emp"}, key = "#result.id")
    public Employee updateEmp(Employee employee) {
        employeeMapper.updateEmp(employee);
        return employee;
    }
    @CacheEvict(cacheNames = {"emp"}, key = "#id")
    public boolean delete(Integer id) {
        employeeMapper.delete(id);
        return true;
    }
    

    自动配置原理

    1. 默认的缓存配置器

     * 直接搜索类 ```CacheAutoConfiguration``` 找到 ```CacheConfigurationImportSelector.selectImports```方法,该方法会返回所有的自动配置类:
    ```org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration```
    `org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration`
    `org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration`
    * 在 `application.yml` 中 设置 `debug: true`,在控制台可以看到默认使用的自动配置类
    ```
    SimpleCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition)
      - @ConditionalOnMissingBean (types: org.springframework.cache.CacheManager; SearchStrategy: all) did not find any beans (OnBeanCondition)
    ```
    

    2. @Cacheable 不能的key不能使用result,因为@Cacheable在方法执行前调用的。

    3. @CachePut 可以使用result中的数据,因为@CachePut在方法执行后调用。

    1. @CacheEvict 默认在方法执行之后执行(如果方法执行出错,将不会执行),可以通过 beforeInvocation=true 设置为在方法之前执行。
  • 相关阅读:
    HDU 4388 To the moon
    HDU 4757 Tree
    HDU 5816 Hearthstone
    hihocoder 1356 分隔相同整数
    HDU 5726 GCD
    POJ3026 Borg Maze(Prim)(BFS)
    POJ1258 Agri-Net(Prim)
    POJ1751 Highways(Prim)
    POJ2349 Arctic Network(Prim)
    POJ1789 Truck History(Prim)
  • 原文地址:https://www.cnblogs.com/Godfunc/p/9316563.html
Copyright © 2020-2023  润新知