Integrating Spring Session with Redis

Keywords: Session Redis Spring Tomcat

There are so many specific features of Spring Session. The specific content can be learned from the document. The author makes a summary. The features of Spring Session include but are not limited to the following:

  • Use GemFire to build httpSession of C/S architecture (not concerned)
  • Use the third-party warehouse to realize the cluster session management, which is often called the distributed session container, replacing the application container (such as the session container of tomcat). For the implementation of warehousing, Spring Session provides three implementations (redis, mongodb, jdbc), among which redis is the most commonly used one. The implementation of the program, using AOP technology, can almost be replaced transparently. (core)
  • It is very convenient to extend cookies and customize the Listener and Filter related to Session.
  • It can be easily integrated with Spring Security, such as findSessionsByUserName, rememberMe, limiting the number of sessions that the same account can be online at the same time (if set to 1, the effect of the previous login can be eliminated), etc

1. Introduce dependency

<dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>2.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

2. Configure filters

Configure the filter in web.xml, noting that it must precede other filters

<filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>

3. Configure redis

@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class RedisHttpSessionConfig {
    @Bean
    public LettuceConnectionFactory connectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration=new RedisStandaloneConfiguration();
        //redis server host ip
        redisStandaloneConfiguration.setHostName("211.149.182.96");
        //Use database number
        redisStandaloneConfiguration.setDatabase(0);
        //redis password
        redisStandaloneConfiguration.setPassword(RedisPassword.of("lgdsj2017"));
        //port
        redisStandaloneConfiguration.setPort(9379);
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }
}

Posted by ron814 on Wed, 01 Apr 2020 06:13:29 -0700