springboot cache 自定义过期时间及自定义缓存key前缀

本篇文章主要是springboot2 中 redis cache中的一些内容,主要包含2个功能点:

  1. 自定义缓存过期时间(全局自定义,每个key不能单独指定)
  2. 自定义缓存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的缓存;

你可能感兴趣的:(java,springboot,缓存,自定义,多租户)