1.spring缓存注解,可以丢在controller,也可以丢在service,也可以丢在mapper。
2.手动操作缓存使用:
java
@Autowired
private CacheManager cacheManager;
3.添加缓存
java
//添加缓存
@Override
@Cacheable(cacheNames = "test", key = "'test_model' + #id",unless="#result == null") //如果结果为空,不缓存
public TestModel selectByIdCache(Long id) {
return baseMapper.selectById(id);
}
//等于代码:
@Override
public TestModel selectByIdCache(Long id) {
TestModel model baseMapper.selectById(id);
if(model!=null){//如果结果为空,不缓存
Cache cache = cacheManager.getCache("test");
cache.put("test_model"+id,model);
}
return model;
}
4.删除缓存
java
//注解删除缓存
@CacheEvict(cacheNames = "test", key = "'test_model' + #bo.id")
@Override
public Boolean updateByBo(TestModelBo bo) {
}
//等于代码:
@Override
public Boolean updateByBo(TestModelBo bo) {
Cache cache = cacheManager.getCache("test");
cache.evict("test_model"+bo.getId());
}
5.清空缓存
java
//注解清空缓存
@CacheEvict(cacheNames = "test", allEntries = true)
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
}
//等于代码:
@Override
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
Cache cache = cacheManager.getCache("test");
cache.clear();
}