一 问题描述
在使用 redis 中的 StringRedisTemplate 后,启动项目,启动失败,报错为:
二 环境背景
背景环境不同可能出现不同的问题,或者相同的问题,列一下背景,方便直接定位解决方案是否可行。
springboot 2.x
三 问题原因
先列一下操作步骤,然后分析错误原因,先引入依赖,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
然后配置属性, 在 application.yml 中 根目录下添加:
redis:
key:
prefix:
authCode: "portal:test:"
expire:
authCode: 120
在 application.yml 的 spring 目录下添加:
redis:
host: localhost
database: 0
port: 6379
password:
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min_idle: 0
timeout: 3000ms
然后在其他地方就可以引用了,类似:
@Autowired
private StringRedisTemplate stringRedisTemplate;
之后启动就会报上文的错误,观察错误提示为 该类找不到,注入不进去,所以网上查了解决办法, 有的说把 @Autowired 改成 @Resource, 试了,不好用,还有其他自己写配置类的,自己注入,感觉比较麻烦,后来发现了问题原因,是包的依赖有问题,基于 springboot 2.x 需要做的特殊修改。
四 解决方案
根据上文, 依赖包有问题,应更改为:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
把 lettuce 排除,更改后再次启动,没有问题了。
五 总结
搞了两个多小时的 注入,看源码之类的,就想知道为啥注入不进去,偶然发现跟 springboot 版本有关,最大的感受就是解决方案一定要附上背景。