Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrate user sessions from HttPsession to Spring redis session (Spring MVC app)

Recently we started using spring redis session as our session manager. We already have our application running in production for the last 8-10 months. There is a mobile app which uses this backend.

When I change the session repository to spring session, all the existing logged in users in the mobile app will be logged out automatically. And then they will have to login again.

Is there anyway to migrate all the existing logged user sessions to Redis instance.

like image 652
Bijesh CHandran Avatar asked Jul 17 '19 12:07

Bijesh CHandran


1 Answers

If I have understood correctly, the answer to live migrating existing connections is no because you are changing out the backend connection. Any new user would need to instantiate connection to the app using the new connection class. Depending on the number of users we are talking about here, it might be possible to allow currently connected users to run on httpsession and all new connections to run off spring redis session. There would be work involved in mapping all existing connected users to stay on httpsession until their connection drains or disconnects and managing the split so that new users use redis session app servers.

If the above is not the case and you are looking for a guide to use Spring Redis Session,then:

First, you will need the spring session module which has data redis, which can be found here: https://github.com/spring-projects/spring-session

Then, you would need to add the following Spring Configuration:

@EnableRedisHttpSession 
public class Config {

    @Bean
    public LettuceConnectionFactory connectionFactory() {
        return new LettuceConnectionFactory(); 
    }

}

The @EnableRedisHttpSession annotation creates a Spring Bean with the name of springSessionRepositoryFilter that implements Filter. The filter is in charge of replacing the HttpSession implementation to be backed by Spring Session. In this instance, Spring Session is backed by Redis. We create a RedisConnectionFactory that connects Spring Session to the Redis Server. We configure the connection to connect to localhost on the default port (6379). For more information on configuring Spring Data Redis, see the reference documentation.

And then you create a redis connection factory:

class AppConfig {

  @Bean
  public LettuceConnectionFactory redisConnectionFactory() {

    return new LettuceConnectionFactory(new RedisStandaloneConfiguration("server", 6379));
  }
}

Sources: https://docs.spring.io/spring-session/docs/current-SNAPSHOT/reference/html5/#httpsession-redis

https://docs.spring.io/spring-data/data-redis/docs/2.2.0.BUILD-SNAPSHOT/reference/html/#reference

like image 161
user138278 Avatar answered Nov 07 '22 22:11

user138278