spring boot cache 提供了一些注解方便做cache应用。
(1)@CacheConfig:主要用于配置该类中会用到的一些共用的缓存配置
(2)@Cacheable:主要方法返回值加入缓存。同时在查询时,会先从缓存中取,若不存在才再发起对数据库的访问。
(3)@CachePut:配置于函数上,能够根据参数定义条件进行缓存,与@Cacheable不同的是,每次回真实调用函数,所以主要用于数据新增和修改操作上。
(4)@CacheEvict:配置于函数上,通常用在删除方法上,用来从缓存中移除对应数据
(5)@Caching:配置于函数上,组合多个Cache注解使用。
注意:
cache相关注解必须在spring所管理的bean容器中,这样才能使缓存生效、启动类中要加入@EnableCaching注解支持缓存
用例如下:
@Service
@CacheConfig(cacheNames = "testCache", cacheManager = "activityMetaRedisCacheManager")
public class TestCacheService implements TestCacheService {
@CachePut(key = "'meta:'+#activityId", unless = "#result == null")
public ActivityMetaDO incrementCount(String activityId, Verb incrementVerb, int inc) {
boolean r = activityMetaStoreBuilder.incrementCount(activityId, incrementVerb, inc);
if (r) {
ActivityMetaDO activityMetaDO = new ActivityMetaDO();
activityMetaDO.setActivityId(activityId);
activityMetaDO = activityMetaStoreBuilder.getByPrimaryKey(activityMetaDO);
return activityMetaDO;
}
return null;
}
@Cacheable(key = "'meta:'+#activityId", unless = "#result == null")
@Override
public ActivityMetaDO getByViewId(String activityId) {
ActivityMetaDO activityMetaDO = new ActivityMetaDO();
activityMetaDO.setActivityId(activityId);
return activityMetaStoreBuilder.getByPrimaryKey(activityMetaDO);
}
@CachePut(key = "'meta:'+#meta.activityId", unless = "#result == null")
@Override
public ActivityMetaDO save(ActivityMetaDO meta) {
return activityMetaStoreBuilder.store(meta);
}
@CacheEvict(key = "'meta:'+#activityId")
@Override
public boolean deleteByViewId(String activityId) {
ActivityMetaDO meta = new ActivityMetaDO();
meta.setActivityId(activityId);
String recommendKey = CacheKey.ACTIVITY_META_RECOMMEND + CustomerConstants.CountryLanguage.fromCountry(meta.getCountry()).getLanguageZone();
long delResult = recommendRedisTemplate.opsForZSet().remove(recommendKey, activityId);
return activityMetaStoreBuilder.deleteByPrimaryKey(meta);
}
//定义缓存RedisCacheManager对象,在缓存时使用
@Bean("activityMetaRedisCacheManager")
@Primary
public RedisCacheManager activityMetaRedisCacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig();
cacheConfig = buildCacheConfig(cacheConfig);
return new SocialRedisCacheManger(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), cacheConfig);
}
相关优秀文章:
https://blog.csdn.net/zlj1217/article/details/80928122
}