使用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);
    }
}
相关文章
相关标签/搜索