spring自带了cache接口,@EnableCaching
表示使用cache,我们通过覆盖CachingConfigurerSupport
类的cacheManager
方法指定用哪种缓存。例如ehcache
,rediscache
。
@Cacheable不要写在同一方法里面
@Cacheable
不要写在同一方法里面,否则无效。例如写在controller里面无效,是因为 @Cacheable
基于代理,同类方法直接调用,并没有用到代理,所以cache无效。
@CacheConfig 是类级别的注解,这里不详述
@Cacheable,@CachePut 的value就是作用的cache名称,返回值就是cache值。
RedisConfig
代码:
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
}
CacheServiceImpl
代码:
@Service
public class CacheServiceImpl {
@Cacheable(value="cache1")// cache1
public int get() {
int num = new Random().nextInt();
return num;
}
@Cacheable(value="cache2")// cache2
public int get2() {
int num = new Random().nextInt();
return num;
}
@CachePut(value={"cache1"})// 更新
public int put() {
return new Random().nextInt();
}
@CacheEvict(value={"cache1,cache2"})// 清空
public void evict() {
}
}
LoginController代码:
@RestController
@RequestMapping("")
public class LoginController {
@Autowired
private CacheServiceImpl cacheService;
@RequestMapping("/login")
public String login(HttpServletRequest request){
int cache1 = cacheService.get();
System.out.println(cache1);
System.out.println(cacheService.get2());
return "fail";
}
@RequestMapping("/put")
public String put(HttpServletRequest request){
cacheService.put();
return "fail";
}
@RequestMapping("/evict")
public String evict(HttpServletRequest request){
cacheService.evict();
return "fail";
}
}
http://localhost:8080/login
刷新2次,发现2次值一样,说明缓存了
先 http://localhost:8080/put
然后 http://localhost:8080/login
发现 1的值变了
http://localhost:8080/evict
,http://localhost:8080/login
发现原来的值被清空了,都是新值