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
配置
- 依賴
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
這個依賴會把其他依賴都引入,例如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沒超時,還是不需要重新登入。