背景
一般情況,跑在tomcat的應(yīng)用,session信息是保存在tomcat容器中。通過client(瀏覽器)帶著cookies(JSESSIONID)來進(jìn)行session的關(guān)聯(lián)备燃。
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>
這個(gè)依賴會把其他依賴都引入并齐,例如redis\spring-session
- application配置
spring.session.store-type=redis
# Session timeout. If a duration suffix is not specified, seconds will be used. 實(shí)際就是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默認(rèn)是true,spring-boot1.x是沒有encode的况褪,所以單點(diǎn)登錄要把這里設(shè)置為false
session超時(shí)時(shí)間
- 優(yōu)先使用
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 區(qū)別:
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
maxInactiveIntervalInSeconds為redis里的超時(shí)時(shí)間,上面的為容器內(nèi)的超時(shí)時(shí)間
直接表現(xiàn):你容器重啟更耻,redis沒超時(shí)测垛,還是不需要重新登錄。