這篇文章介紹一下在springboot項目中整合Spring Session,將session會話信息保存到Redis中,防止重啟應用導致會話丟失。
第一步
創建一個springboot項目,添加spring-session-redis的依賴,因為要用到reids,所以要把redis相關依賴也加進來。
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency></dependencies>
第二步
在spplication.yml中配置命名空間和redis的連接信息。
spring:session:redis:save-mode: on_set_attributenamespace: spring:sessionredis:host: localhostport: 6379database: 0password: mhxy1218
第三步
在啟動類上添加@EnableRedisHttpSession注解。
第四步
在項目中使用HttpSession,創建一個控制器類,然后添加兩個接口分別用于設置和獲取session。
package cn.edu.sgu.www.session.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;/*** @author heyunlin* @version 1.0*/
@RestController
@RequestMapping("/session")
public class SessionController {@GetMapping("/getSession")public String getSession(HttpSession session, HttpServletRequest request) {Object name = session.getAttribute("name");// 查看請求頭Enumeration<String> headerNames = request.getHeaderNames();while (headerNames.hasMoreElements()) {String element = headerNames.nextElement();System.out.println(element);}return name.toString();}@GetMapping("/setSession")public void setSession(HttpSession session, String name) {session.setAttribute("name", name);}}
第四步
啟動項目,在瀏覽器輸入以下網址,設置name為沐雨橙風ιε
http://localhost:8080/session/setSession?name=%E6%B2%90%E9%9B%A8%E6%A9%99%E9%A3%8E%CE%B9%CE%B5
然后,再訪問獲取session的接口
http://localhost:8080/session/getSession
第五步
查看瀏覽器cookie,按F12打開瀏覽器控制臺,點擊網絡查看剛剛發起的請求攜帶的cookile數據。
把這長串字符串復制出來
第六步
清空瀏覽器,訪問獲取session數據的接口。
這時候發現已經獲取不到了,這是因為清理緩存會把瀏覽器的cookie數據刪除,所以請求時沒有攜帶cookile請求頭。
第七步
通過postman訪問/session/getSession,攜帶請求頭cookie,其內容為
SESSION=ZDcyNGFlNzgtYzUyYS00NGFjLTkwYzgtMzRiYWNjNjE1Y2Y0
第八步
重啟項目,然后再獲取session,這時候數據還在~
好了,文章就分享到這里了,代碼已經上傳到gitee~
spring boot整合spring-session-redis案例項目https://gitee.com/muyu-chengfeng/spring-session-redis.git?