如何在不同站點(web服務進程)之間共享會話 Session 呢,原理很簡單,就是把這個 Session 獨立存儲在一個地方,所有的站點都從這個地方讀取 Session。
通常我們使用 Redis 來解決這個問題
- Spring Boot 2.1.8
- Redis 5.0.3
本章解決前面文章 Spring Boot 利用 nginx 實現生產環境的偽熱更新 產生的session共享問題。
1 Redis 准備
本示例使用 Redis 5.0.3 操作系統為 Mac ,關於如何安裝 redis 請自行搜索。
2 建立 Spring Boot 測試項目
2.1 新建 Spring Boot Maven 示例工程項目
注意:是用來 IDEA 開發工具
- File > New > Project,如下圖選擇
Spring Initializr
然后點擊 【Next】下一步 - 填寫
GroupId
(包名)、Artifact
(項目名) 即可。點擊 下一步
groupId=com.fishpro
artifactId=sharedsession - 選擇依賴
Spring Web Starter
前面打鈎。 - 項目名設置為
spring-boot-study-sharedsession
.
2.2 依賴引入 Pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
</dependencies>
2.3 配置文件 application 中配置
server:
port: 8084
#2.x版本中由於引入了不同客戶端,需要指定配置哪種連接池
#jedis客戶端
spring:
cache:
type: redis
redis:
host: 127.0.0.1
port: 6379
password:
database: 0
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
2.4 加入測試代碼
開啟 RedisSession
新建 RedisSessionConfig 類,使用 @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600) 注解,其中maxInactiveIntervalInSeconds表示默認的 Session 時間
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class RedisSessionConfig {
}
編寫一個 Controller 文件設置與讀取 Session
@EnableRedisHttpSession
@RestController
public class IndexController {
@GetMapping("")
public String index(HttpServletRequest request){
request.getSession().setAttribute("username", "公眾號 程序魚");
request.getSession().setMaxInactiveInterval(10*1000);
String username = (String)request.getSession().getAttribute("username");
return "username"+username+ " session_id:"+request.getSession().getId();
}
}
2.5 測試效果
在不同的端口下啟動本項目查 輸入