javaspringspring-bootredisspring-boot-starter

required a bean of type 'org.springframework.session.data.redis.RedisIndexedSessionRepository' that could not be found


I have a project which uses spring boot which uses spring-boot-starter-data-redis to manage distributed session, which was running fine.

I tried to migrate to spring boot 3, i was getting the below error.

Consider defining a bean of type 'org.springframework.session.data.redis.RedisIndexedSessionRepository' in your configuration

To fix the above error I have defined a bean as below.

 @Bean
 public RedisIndexedSessionRepository redisIndexedSessionRepository(RedisTemplate<String, Object> redisTemplate) {
        return new RedisIndexedSessionRepository(redisTemplate);
    }

After this a new error popped up as below.

 required a single bean, but 2 were found:
    - redisIndexedSessionRepository: defined by method 'redisIndexedSessionRepository' in class path resource [com/google/ussm/config/UssmConfig.class]
    - sessionRepository: defined by method 'sessionRepository' in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]

To fix this error the below code came into handy.

 @Primary
    @Bean
    public RedisIndexedSessionRepository redisIndexedSessionRepository(RedisTemplate<String, Object> redisTemplate) {
        return new RedisIndexedSessionRepository(redisTemplate);
    }

Now the the application is running fine , but the SessionExpiredEvent and SessionDeletedEvent not being fired in the application.

Also I have noticed that in redis :index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME is missing , which constitutes the above problem.

Requesting any suggestion to fix this error.

Thanks in advance.


Solution

  • There is support for spring boot 3.2.0 for this.

    Change @EnableRedisHttpSession to --->@EnableRedisIndexedHttpSession. This change will configure RedisIndexedSessionRepository over RedisSessionRepository .

    By using RedisIndexedSessionRepository you can now start to listen to SessionCreatedEvent, SessionDeletedEvent, SessionDestroyedEvent and SessionExpiredEvent events.

    For detailed explanation visit this. For listening to Session Events visit this.


    And in your session security configuration.

    add the below to save the sessions in the repository. Read more about here

    http.securityContext((securityContext) -> securityContext
                    .requireExplicitSave(false)
            )