Java基础、中级、高级、架构面试资料

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

JAVA herman 2690浏览
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

最近在 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();
    }

最终完美解决!

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » redisCacheManager nested exception is java.lang.IllegalArgumentException: TTL duration must not be null!