Integrate Spring Session with Redis

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

  • Use GemFire ​​to build httpSession with C/S architecture (don't pay attention)
  • Use a third-party repository to implement cluster session management, which is often referred to as a distributed session container, instead of an application container (such as a tomcat session container). The implementation of warehousing, Spring Session provides three implementations (redis, mongodb, jdbc), of which redis is the most commonly used. The realization of the program, using AOP technology, can be replaced almost transparently. (core)
  • It is very convenient to extend Cookie and custom Session related Listener and Filter.
  • It can be easily integrated with Spring Security, adding functions such as findSessionsByUserName, rememberMe, limiting the number of sessions that can be online at the same time for the same account (for example, setting it to 1 can achieve the effect of removing the previous login), etc.

1. Introduce dependencies

<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 the filter

Configure the filter in web.xml, note that the filter must be before 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服务器主机ip
        redisStandaloneConfiguration.setHostName("127.0.0.1");
        //使用第几个数据库
        redisStandaloneConfiguration.setDatabase(0);
        //redis密码
        redisStandaloneConfiguration.setPassword(RedisPassword.of("lgdsj2017"));
        //端口
        redisStandaloneConfiguration.setPort(9379);
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325808171&siteId=291194637