使用Redis集成Spring Session

Spring-Session具體的特性很是之多,具體的內容能夠從文檔中瞭解到,筆者作一點本身的總結,Spring Session的特性包括但不限於如下:java

  • 使用GemFire來構建C/S架構的httpSession(不關注)
  • 使用第三方倉儲來實現集羣session管理,也就是常說的分佈式session容器,替換應用容器(如tomcat的session容器)。倉儲的實現,Spring Session提供了三個實現(redis,mongodb,jdbc),其中redis使咱們最經常使用的。程序的實現,使用AOP技術,幾乎能夠作到透明化地替換。(核心)
  • 能夠很是方便的擴展Cookie和自定義Session相關的Listener,Filter。
  • 能夠很方便的與Spring Security集成,增長諸如findSessionsByUserName,rememberMe,限制同一個帳號能夠同時在線的Session數(如設置成1,便可達到把前一次登陸頂掉的效果)等等

一、引入依賴web

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

二、配置過濾器redis

在web.xml中配置過濾器,注意該過濾器必須在其餘過濾器以前spring

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

三、配置redismongodb

@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);
    }
}
相關文章
相關標籤/搜索