1、Spring Cache 的使用
-
@Cacheable 注解
主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,只有使用public定义的方法才可以被缓存,而 private 方法、protected 方法或者使用 default 修饰符的方法都不能被缓存, 当在一个类上使用注解时,该类中每个公共方法的返回值都将被缓存到指定的缓存项中或者从中移除
cacheNames / value:用于指定缓存存储的集合名
key:缓存对象存储在Map集合中的key值,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpringEL表达式
@Cacheable(key = "#p0") //使用函数第一个参数作为缓存的key值
condition:缓存对象的条件,非必需,也需使用SpringEL表达式,只有满足表达式条件的内容才会被缓存
// 表示只有当第一个参数的长度小于3的时候才会被缓存 @Cacheable(key = "#p0", condition = "#p0.length() < 3")
unless:另外一个缓存条件参数,非必需,需使用SpringEL表达式。它不同于condition参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以对result进行判断
@Cacheable(value = "params_details", key = "#publicKey", unless = "#result == null ")
condition 与 unless 作用都是排除满足条件的结果(满足条件不进行缓存)
condition 与 unless 的区别:
- condition:对参数进行判断
- unless:对结果进行判断
sync:是否使用异步模式。
-
获取缓存中的参数
CacheManager负责对缓存的增删改查, CacheManager的缓存的介质可配置, 如:ConcurrentMap/EhCache/Redis等。当没有加入EhCache或者Redis依赖时默认采用concurrentMap实现的缓存,是存在内存中,重启服务器则清空缓存
@Resouce private final CacheManager cacheManager; public Object getCacheValue() { return cacheManager.getCache(CACHE_KEY); }
2、Spring Cache 存取缓存数据
-
设置缓存的介质
默认采用concurrentMap实现的缓存,是存在内存中,重启服务器则清空缓存
设置 redis 为缓存介质
spring: cache: type: redis redis: host: 127.0.0.1 port: 6379 password: 123456
-
添加依赖
<!--多级缓存--> <dependency> <groupId>com.pig4cloud.plugin</groupId> <artifactId>multilevel-cache-spring-boot-starter</artifactId> <version>1.0.1</version> </dependency>
-
向缓存中存储数据
使用 @Cacheable 注解的方式做缓存操作:
value:redis 分组集合
key:分组集合中指向存储对象的键
unless:设置缓存条件(排除符合条件的结果)
@RequestMapping(method = RequestMethod.POST) @Cacheable(value = "Test" ,key = "'Cache'", unless = "#result == null") public String cache() { return "CacheValue"; }
-
从缓存中获取数据
@Autowired private final CacheManager cacheManager; @RequestMapping(method = RequestMethod.GET) public Object getCacheValue() { Cache cache = cacheManager.getCache("Test"); if (cache != null && cache.get("Cache") != null) { return cache.get("Cache").get(); } return "error"; }