昨天集成redis时,发现一个很奇怪的现象,就是明明已经设置了过期时间,但是过期时间一直没生效。查了半天,才发现是自己的一个小习惯导致的问题。先看有问题的代码:

private CacheManager redisCacheManager(){
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
    defaultCacheConfig.entryTtl(Duration.ofSeconds(10));

    Map<String, RedisCacheConfiguration> map = new HashMap<>();
    map.put("ydms",defaultCacheConfig);
    RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter,defaultCacheConfig,map);
    return cacheManager;
}

查了半天,才发现是 defaultCacheConfig.entryTtl(Duration.ofSeconds(10));
这一行写的有问题。改成以下的样子就好了:

private CacheManager redisCacheManager(){
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
    //关键行
    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(10));

    Map<String, RedisCacheConfiguration> map = new HashMap<>();
    map.put("ydms",defaultCacheConfig);
    RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter,defaultCacheConfig,map);
    return cacheManager;
}

这是为什么呢?我们来看看entryTtl 这个方法。我们来看
RedisCacheConfiguration这个类的entryTtl方法的实现。


    public RedisCacheConfiguration entryTtl(Duration ttl) {
        Assert.notNull(ttl, "TTL duration must not be null!");
        return new RedisCacheConfiguration(ttl, this.cacheNullValues, this.usePrefix, this.keyPrefix, this.keySerializationPair, this.valueSerializationPair, this.conversionService);
    }

entryTtl并不是对当前对象的值的设置,而是会返回一个新的RedisCacheConfiguration对象。如果我们只是写

defaultCacheConfig.entryTtl(Duration.ofSeconds(10));

那么它不会起到任何作用。
在调度的过程中,为了更方便的看到缓存时间的效果,我通过redis的ttl命令来查看对象的过期时间。首先,通过:keys * 来查找所有的key, 这个命令会返回 redis里所有的key.然后再通过 ttl <key> 来查看key的过期时间设置。以下是从redis官网截取的命令示例。

redis> KEYS \*name\*

1) "lastname"
2) "firstname"

redis> KEYS a??

1) "age"

redis> KEYS \*

1) "lastname"
2) "age"
3) "firstname"

redis>
redis> SET mykey "Hello"

"OK"

redis> EXPIRE mykey 10

(integer) 1

redis> TTL mykey

(integer) 10

redis>

参考文档:
https://redis.io/commands


竣峰
164 声望3 粉丝