【问题标题】:Cannot use RedisIndexedSessionRepository in service无法在服务中使用 RedisIndexedSessionRepository
【发布时间】:2021-01-25 07:43:56
【问题描述】:

对于我的 spring-boot 应用程序(2.3.3.RELEASE,Java 11),我使用 spring session,这是一个标准的依赖项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>

应用程序按预期工作,会话存储在 redis 中并由 spring 管理。

但是我想手动从 Redis 中删除会话。为此,我注意到 spring 在 RedisHttpSessionConfiguration 中有一个用于会话存储库的 bean(第 119 行):

@Bean
public RedisIndexedSessionRepository sessionRepository() {

我决定重用它。不幸的是,当我在我的服务中尝试这样做时:

@Service
@RequiredArgsConstructor
public class SessionService {
    private final RedisIndexedSessionRepository sessionRepository;

应用程序启动时出现以下错误

Failed to instantiate [org.springframework.session.data.redis.RedisIndexedSessionRepository]: Circular reference involving containing bean 'org.springframework.boot.autoconfigure.session.RedisSessionConfiguration$SpringBootRedisHttpSessionConfiguration' - consider declaring the factory method as static for independence from its containing instance. Factory method 'sessionRepository' threw exception; nested exception is java.lang.IllegalStateException: RedisConnectionFactory is required

UPD。我发现如果我将 RedisIndexedSessionRepository 添加到我的服务 Spring 以某种方式不会执行负责在 RedisHttpSessionConfiguration 中设置 redisConnectionFactory 的代码(自动连接方法 setRedisConnectionFactory,第 204 行)。但是,如果我从我的服务中删除 RedisIndexedSessionRepository,则会触发上述方法。我也尝试创建自己的 bean RedisConnectionFactory,但它没有解决这个问题。

啊,我在上面的 RedisHttpSessionConfiguration 中找到了这条评论:

 * Exposes the {@link SessionRepositoryFilter} as a bean named
 * {@code springSessionRepositoryFilter}. In order to use this a single
 * {@link RedisConnectionFactory} must be exposed as a Bean.

但还是不明白如何在服务中使用 RedisIndexedSessionRepository

有人可以建议如何处理这个问题以及如何在应用程序中使用这个存储库吗?

【问题讨论】:

    标签: spring-boot spring-security spring-session


    【解决方案1】:

    似乎 RedisIndexedSessionRepository 不能简单地自动装配,我们已经手动完成了,例如:

    private final RedisIndexedSessionRepository sessionRepository;
    
    public SessionService(RedisTemplate<Object, Object> redisTemplate) {
        this.sessionRepository = new RedisIndexedSessionRepository(redisTemplate);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-21
      • 2019-01-31
      • 2016-09-14
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多