spring-session

背景

一般情况,跑在tomcat的应用,session信息是保存在tomcat容器中。通过client(浏览器)带着cookies(JSESSIONID)来进行session的关联。

spring-session

Spring Session makes it trivial to support clustered sessions without being tied to an application container specific solution. It also provides transparent integration with:

HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way, with support for providing session IDs in headers to work with RESTful APIs

WebSocket - provides the ability to keep the HttpSession alive when receiving WebSocket messages

WebSession - allows replacing the Spring WebFlux’s WebSession in an application container neutral way

支持替换3种session类型:HttpSession、WebSocket、WebSession

配置

  • 依赖

    org.springframework.session
    spring-session-data-redis

    
      io.lettuce
      lettuce-core
    

这个依赖会把其他依赖都引入,例如redis\spring-session

  • application配置
spring.session.store-type=redis
# Session timeout. If a duration suffix is not specified, seconds will be used. 实际就是duration类,支持h\m\s
server.servlet.session.timeout=3600s
#Sessions flush mode.  
spring.session.redis.flush-mode=ON_SAVE
# Namespace for keys used to store sessions. 保存在redis的前缀 分隔
spring.session.redis.namespace=spring:session
# Redis server host.
spring.redis.host=xxx.xxx.xxx.xxx
# Login password of the redis server.
spring.redis.password=
#Redis server port.
spring.redis.port=6379

spring.session.redis.flush-mode: 枚举类型ON_SAVE、IMMEDIATE

  • ON_SAVE http response为committed才提交

  • IMMEDIATE立即保存

  • cookies序列化

    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("JSESSIONID");
        serializer.setCookiePath("/");
        serializer.setUseBase64Encoding(false);
        serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
        return serializer;
    }

setUseBase64Encoding spring-boot2.0默认是true,spring-boot1.x是没有encode的,所以单点登录要把这里设置为false

session超时时间

  • 优先使用spring.session.timeout ,如果不存在则使用server.servlet.session.timeout

原文:

For setting the timeout of the session you can use the spring.session.timeout property. If that property is not set, the auto-configuration falls back to the value of server.servlet.session.timeout.

  • 与maxInactiveIntervalInSeconds 区别:
    @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
    maxInactiveIntervalInSeconds为redis里的超时时间,上面的为容器内的超时时间

直接表现:你容器重启,redis没超时,还是不需要重新登录。

资料

Spring Session:里面有Samples and Learn
spring-session doc

你可能感兴趣的:(spring-session)