1.spring缓存注解,可以丢在controller,也可以丢在service,也可以丢在mapper。
2.手动操作缓存使用:
@Autowired
private CacheManager cacheManager;
3.添加缓存
@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.删除缓存
@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.清空缓存
@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();
}