本文共 1394 字,大约阅读时间需要 4 分钟。
本篇文章主要是springboot2 中 redis cache中的一些内容,主要包含2个功能点:
自定义缓存过期时间(全局自定义,每个key不能单独指定)
自定义缓存key前缀
废话不多说,上代码
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
private static final String SYSTEMCACHE_REDIS_KEY_PREFIX = "system:cache";
private static final String SYSTEMCACHE_TTL_OFDAY = "system.cache.ttlOfDay";
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
@Override
public CacheManager cacheManager() {
// 设置系统缓存过期时间为默认30天以及添加自定义前缀
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(
Duration.ofDays(30))
.computePrefixWith(cacheKeyPrefix()); // 设置缓存有效期一小时
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public CacheKeyPrefix cacheKeyPrefix() {
return new CacheKeyPrefix() {
@Override
public String compute(String cacheName) {
String cid = getCid();//此方法需要自己实现,获取租户编码
StringBuilder sBuilder = new StringBuilder(100);
sBuilder.append(SYSTEMCACHE_REDIS_KEY_PREFIX).append(":");
if (StringUtil.isNotBlank(cid)) {
sBuilder.append(cid).append(":");
}
sBuilder.append(cacheName).append(":");
return sBuilder.toString();
}
};
}
}
用法:
@Cacheable(value = {"MenuTreeByRoles"})
public List> selectMenuTreeByRoles(String roleIds) {...}
则最终以生成system:cache:cid:MenuTreeByRoles为key的缓存;
转载地址:https://blog.csdn.net/weixin_33520510/article/details/114925420 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!