配置redis缓存失效时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hzt_fighting_up/article/details/78507896

最近想利用redis缓存做一个简陋版的类似腾讯新闻这样的查看新闻的网页。用了缓存以后,添加新闻缓存没有更新,想使用缓存的失效时间做到数据库缓存一致性。刚开始做的时候认为使用@CachePut注解会起到更新缓存的作用,设置了cacheName和key都和查找方法中的@Cacheable中的key和cacheName的一样,然而并没有成功,反而是被替换了,想想hashMap就能理解这个问题了。

如何设置,通过RedisCacheManage,看名字就知道应该通过它来设置
RedisCacheManage源码简单介绍

1.成员变量:

private final Log logger;
private final RedisOperations redisOperations;
private boolean usePrefix;
private RedisCachePrefix cachePrefix;
private boolean loadRemoteCachesOnStartup;
private boolean dynamic;
private long defaultExpiration;
private Map<String, Long> expires;
private Set<String> configuredCacheNames;
private final boolean cacheNullValues;

我们应该重点关注的是defaultExpiration和Map< String, Long> expires,只有这两个元素是和缓存失效时间有关的

2.构造函数

public RedisCacheManager(RedisOperations redisOperations) {
        this(redisOperations, Collections.emptyList());
    }

public RedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames) {
    this(redisOperations, cacheNames, false);
}

public RedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames, boolean cacheNullValues) {
    this.logger = LogFactory.getLog(RedisCacheManager.class);
    this.usePrefix = false;
    this.cachePrefix = new DefaultRedisCachePrefix();
    this.loadRemoteCachesOnStartup = false;
    this.dynamic = true;
    this.defaultExpiration = 0L;
    this.expires = null;
    this.redisOperations = redisOperations;
    this.cacheNullValues = cacheNullValues;
    this.setCacheNames(cacheNames);
}

构造函数依次调用,第一个构造函数调用第二个构造函数,第二个构造函数调用第三个构造函数。我们在使用的时候都是用的第一个构造函数,传递进一个redisTemplate。在第三个构造函数中defaultExpiration = 0L,过期时间为0,表示缓存用不失效,expires = null表示没有为任何缓存设置缓存失效时间

3.设置缓存失效的方法

public void setExpires(Map<String, Long> expires) {
        this.expires = expires != null?new ConcurrentHashMap(expires):null;
    }

注意:传入的参数为Map类型的
如果传入的参数不为null。则将该值传递给expires,并且通过ConcurrentHashMap(expires)包装了一下,保证是线程安全的。

4.用到expires参数的方法

protected long computeExpiration(String name) {
Long expiration = null;
if(this.expires != null) {
expiration = (Long)this.expires.get(name);
}

    return expiration != null?expiration.longValue():this.defaultExpiration;
}

通过get方法获得对应缓存区域的缓存失效时间。如果没有设置缓存失效时间,则默认永远不失效

5.配置缓存失效时间
在配置redis的配置文件中进行修改,我用的是java配置文件

     /**
     * redis缓存管理器
     * */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        Map<String, Long> expires = new HashMap<String, Long>();
        expires.put("news", 60L);
        redisCacheManager.setExpires(expires);
        return redisCacheManager;
    }

时间是以秒作为单位的,Map中对应的键值对为缓存名和对应的缓存失效时间

猜你喜欢

转载自blog.csdn.net/Hzt_fighting_up/article/details/78507896