java cache 有效期_springboot cache 自定义过期时间及自定义缓存key前缀
发布日期:2021-06-24 15:01:28 浏览次数:4 分类:技术文章

本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java实验一目的_Java实验报告(实验一)
下一篇:python post方法与点击请求_【学习】python+requests进行get、post方法接口测试

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月23日 02时40分04秒