Search code examples
javaredisspring-cache

RedisTemplate getExpire() return unexpect value in Springcache


I wanne refresh cache while near expiry. So I override part of springcache, and manage cache in my own redisCacheManager.

Everything works fine, but when running the "get" method, unexpected values ​​are returned in my own CustomizedRedisCache. At that time, the cache key in redis was indeed the same as the "cacheKey" property.

    @Override
    public ValueWrapper get(final Object key) {
        ValueWrapper valueWrapper = super.get(key);
        if (null != valueWrapper) {
            String cacheKey = this.createCacheKey(key);
            log.info("cache name in redis = {}", cacheKey);
            Long ttl = this.redisTemplate.getExpire(cacheKey, TimeUnit.SECONDS);
            log.info("{}s before expire ", ttl);
        }
        return valueWrapper;
    }

Field ttl always return -2 .And I dont understand what that means.


Solution

  • From redis documentations:

    Starting with Redis 2.8 the return value in case of error changed:

    • The command returns -2 if the key does not exist.
    • The command returns -1 if the key exists but has no associated expire.

    I would recommend you to make sure that the key is correct and really exist in redist when getExpire is executed