起因:
公司的项目,发现某些模块虽然业务中使用到了:
@Autowired
private RedisTemplate redisTemplate;
但是我本地配置文件都没有配置相关redis的配置,居然成功启动了,后来查了下发现redisTemplate的相关操作源码中都会去先调用excute方法:
@Override
public Boolean hasKey(K key) {
byte[] rawKey = rawKey(key);
return execute(connection -> connection.exists(rawKey), true);
}
所以都是使用的时候先连接再操作
但是用户模块没有配置redis的相关参数却会报错,日志显示无法创建名为enableRedisKeyspaceNotificationsInitializer:
[ERROR] 2020-12-01 11:21:19.425 [restartedMain] SpringApplication:Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/boot/autoconfigure/session/RedisSessionConfiguration$SpringBootRedisHttpSessionConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis;
后查看其他模块DEBUG启动日志发现关于:
[DEBUG] 2020-12-01 10:21:02.067 [restartedMain] DefaultListableBeanFactory:Autowiring by type from bean name 'stringRedisTemplate' via factory method to bean named 'redisConnectionFactory'
和用户模块的不一样:
[DEBUG] 2020-12-01 11:21:05.910 [restartedMain] DefaultListableBeanFactory:Creating shared instance of singleton bean 'sessionRepository'
查看源码发现这个bean
package org.springframework.session.data.redis;
/**
* A {@link SessionRepository} implementation that uses Spring Data's
* {@link RedisOperations} to store sessions is Redis.
* <p>
* This implementation does not support publishing of session events.
*
* @author Vedran Pavic
* @since 2.2.0
*/
public class RedisSessionRepository implements SessionRepository<RedisSessionRepository.RedisSession> {
可见启动的时候会需要将session存入redis
再看POM就可以确定是:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
的问题了,注释了这个依赖后,用户模块果然可以启动,但是为什么需要这个依赖呢?
根据文章SpringBoot+SpringSession+Redis实现session共享及唯一登录,通过比较redis中存储的sessionId,确认是否唯一登录。
但是我公司的项目使用了JWT,每次接口调用都会经过gateway,去判断JWT所携带的token和redis中存的是否相同,以此来实现单点登录,故不需要依赖spring-session-data-redis
网友评论