• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

@Cacheable设置过期时间

武飞扬头像
Kinkkkk
帮助5

@Cacheable设置过期时间

参考:https://blog.csdn.net/liuyueyi25/article/details/118422143

使用@Cacheable时,无法直接设置过期时间,需要自定义RedisCacheManager来实现ttl设置。

注意:项目中已配置了RedisCacheManager需要在原配置的bean上添加注解**@Primary**,以免造成干扰

	/**
		自定义RedisCacheManager,用于在使用@Cacheable时设置ttl
	 */
	@Bean
	public RedisCacheManager selfCacheManager(RedisTemplate<String, Object> redisTemplate) {
		RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
		RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
		return new TtlRedisCacheManager(redisCacheWriter, redisCacheConfiguration);
	}

其中return的TtlRedisCacheManager定义如下:

public class TtlRedisCacheManager extends RedisCacheManager {
    public TtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] cells = StringUtils.delimitedListToStringArray(name, "=");
        name = cells[0];
        if (cells.length > 1) {
            long ttl = Long.parseLong(cells[1]);
            // 根据传参设置缓存失效时间,默认单位是秒
            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));
        }
        return super.createRedisCache(name, cacheConfig);
    }
}
学新通

使用时在value/cacheNames结尾拼接 =多少秒

//value、cacheNames是等效的,ttl=600s,unless是不缓存的结果(为null时不缓存)
@Cacheable(value = "p_user=600",key = "#menu '_' #type '_' #userId",cacheManager = "selfCacheManager", unless = "#result == null")
public User getUser(...){
    xxx
}

//当前方法执行时对应的key失效,也可以用@CachePut在当前方法执行时更新key
@CacheEvict(cacheNames = "p_user",key = "#p.menu '_' #p.type '_' #p.user")
public boolean setUser(User p){
    xxx
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfhgfeh
系列文章
更多 icon
同类精品
更多 icon
继续加载