redisCacheManager nested exception is java.lang.IllegalArgumentException: TTL duration must not be null!

最近在 SpringBoot 1.x 升级到 2.x 上遇到了不少异常。

项目越大,项目越老,升级 SpringBoot 带来的风险也越大。我在整个升级的过程中已经遇到了十几个冲突,报错,编译异常等问题。

但唯独,nested exception is java.lang.IllegalArgumentException: TTL duration must not be null! 这个问题,没百度到答案。

不得已,只能使用我的谷歌,有几篇英文记录了这个问题,我这里整理记录一下,方便其他网友排错!

CacheManager 在 SpringBoot 1.x 中的用法:

@Bean
public CacheManager redisCacheManager(RedisTemplate<?, ?> redisTemplate) {
    CacheManager cacheManager = new RedisCacheManager(redisTemplate);
    return cacheManager;
}

这种用法在 SpringBoot 2.x 中已经无法使用了。SpringBoot 2.x 用法:

@Bean
public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(null));
    return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
            .cacheDefaults(redisCacheConfiguration).build();
}

这个问题就产生在 entryTtl(null) 上。完整的异常信息如下:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisCacheManager' defined in class path resource [com/xttblog/config/RedisCacheConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.CacheManager]: Factory method 'redisCacheManager' threw exception; nested exception is java.lang.IllegalArgumentException: TTL duration must not be null!

解决办法就是设置 entryTtl,entryTtl() 方法中有一个判断:

Assert.notNull(ttl, "TTL duration must not be null!"); 

下面给出一个正确用法:

@Bean
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(3600));
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

最终完美解决!

redisCacheManager nested exception is java.lang.IllegalArgumentException: TTL duration must not be null!

: » redisCacheManager nested exception is java.lang.IllegalArgumentException: TTL duration must not be null!

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/252268.html

(0)
上一篇 2022年5月4日
下一篇 2022年5月4日

相关推荐

发表回复

登录后才能评论