Springboot关于yml文件配置Redis参数不生效,总是默认连接到localhost问题

/ 0条评论 / 0 个点赞 / 790人阅读

问题的症状描述为,properties与yml文件中对于redis参数的配置启动时候不生效,总是会无视配置文件参数默认连接到localhost:6379。

出现上述问题是因为boot在1.X和2.X版本的时候对redis的配置参数做了升级,如果boot是2.X而配置文件时参数使用1.X模式配置,那么boot装载配置文件的时候读不到redis的配置参数,也就是说参数配置的格式不对。

在 Spring Boot 中使用 Redis,有两组配置参数可供选择:spring.redis和spring.data.redis。spring.redis是 Spring Boot 1.x 版本中使用的配置前缀,用于配置与 Redis 相关的参数,如连接地址、端口、密码等。配置文件参数如下:

spring.redis.host=localhost

spring.redis.port=6379

spring.redis.password=mypassword


spring.data.redis则是从 Spring Boot 2.x 版本开始引入的新的配置前缀,也用于配置 Redis 的相关参数。配置文件参数如下:

spring.data.redis.host=localhost

spring.data.redis.port=6379

spring.data.redis.password=mypassword

二者对比多了data作为前缀。

实际上,spring.data.redis 是对 spring.redis 的扩展和增强,提供了更多的 Redis 配置选项和功能,例如支持 Redis Sentinel 和 Redis Cluster 等模式。因此,在 Spring Boot 2.x 及以上的版本中,推荐使用spring.data.redis 进行 Redis 相关的配置。但对于 Spring Boot 1.x 版本仍然可以使用进行配置。

因此如果发现配置不生效请检查springboot版本与参数配置是否一致,此外,配置参数的缩进以及额外依赖的包中存在application.properties或者application.yml文件也会影响参数的生失效。因为配置文件参数在装配阶段如果已经存在了有效配置,后面存在的配置参数的参数就会被跳过。