springboot配置基於redis的session
阿新 • • 發佈:2021-06-21
springboot配置基於redis的session
-
為什麼要使用session共享?
因為在多個伺服器之間我準確認識同一客戶端,以方便儲存會話狀態。
-
只有redis這一種方案嗎?或者說基於redis的Session能有什麼優勢?
不是的,我們的目的是要讓會話狀態得以儲存和準確識別,比如nginx基於hash來進行輪詢,那每次會話都會到同樣一臺服務上,也可以保證會話狀態。
而且,本質是我們把會話狀態放入nosql資料庫,每次從資料庫中讀取還原。基於redis方案比較成熟還有就是redis記憶體操作等其它優勢,可以去redis官網瞭解。
通過redis來實現Session共享
-
引入必要的pom依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
-
編寫必要的配置資訊
# redis 配置 spring: redis: database: 0 cluster: max-redirects: 3 nodes: - 192.168.15.208:7001 - 192.168.15.208:7002 - 192.168.15.208:7003 - 192.168.15.208:7004 - 192.168.15.208:7005 - 192.168.15.208:7006 #password: 1234 lettuce: pool: max-active: 1000 max-wait: -1 max-idle: 10 min-idle: 5 timeout: 3000 data: redis: repositories: enabled: false
-
啟動基於redis的session共享,在啟動類上新增@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
@SpringBootApplication @EnableCaching @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800) public class SaleWhiteBoardApplication { public static void main(String[] args) { SpringApplication.run(SaleWhiteBoardApplication.class, args); } }
maxInactiveIntervalInSeconds: 設定 Session 失效時間,使用 Spring Session 之後,原 Spring Boot 配置檔案
application.yml
中的server.session.timeout
屬性不再生效