spring Session 提供了一套用于管理用戶 session 信息的API和實現。
Spring Session為企業級Java應用的session管理帶來了革新,使得以下的功能更加容易實現:
- 編寫可水平擴展的原生云應用。
- 將session所保存的狀態卸載到特定的外部session存儲中,如Redis或Apache Geode中,它們能夠以獨立于應用服務器的方式提供高質量的集群。
- 當用戶使用WebSocket發送請求的時候,能夠保持HttpSession處于活躍狀態。
- 在非Web請求的處理代碼中,能夠訪問session數據,比如在JMS消息的處理代碼中。
- 支持每個瀏覽器上使用多個session,從而能夠很容易地構建更加豐富的終端用戶體驗。
- 控制session id如何在客戶端和服務器之間進行交換,這樣的話就能很容易地編寫Restful API,因為它可以從HTTP 頭信息中獲取session id,而不必再依賴于cookie。
Spring-Boot集成Spring session并存入redis
添加maven依賴
Redis的相關依賴可以看之前的內容,這里需要增加如下依賴。
1
2
3
4
|
< dependency > < groupId >org.springframework.session</ groupId > < artifactId >spring-session</ artifactId > </ dependency > |
Java代碼實現
增加HttpSessionConfig。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.core.config; import org.springframework.context.annotation.Bean; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.session.web.http.HeaderHttpSessionStrategy; import org.springframework.session.web.http.HttpSessionStrategy; @EnableRedisHttpSession (maxInactiveIntervalInSeconds = 100 , redisNamespace = "xxxx" ) public class HttpSessionConfig { @Bean public HttpSessionStrategy httpSessionStrategy() { return new HeaderHttpSessionStrategy(); } } |
其中注解 EnableRedisHttpSession 創建了一個名為springSessionRepositoryFilter的Spring Bean,該Bean實現了Filter接口。該filter負責通過 Spring Session 替換HttpSession從哪里返回。這里Spring Session是通過 redis 返回。
類中的方法 httpSessionStrategy(),用來定義Spring Session的 HttpSession 集成使用HTTP的頭來取代使用 cookie 傳送當前session信息。如果使用下面的代碼,則是使用cookie來傳送 session 信息。
1
2
3
4
|
@Bean public HttpSessionStrategy httpSessionStrategy() { return new CookieHttpSessionStrategy(); } |
使用HTTP的頭,會看到如下信息
1
2
3
4
5
6
7
8
|
-- response -- 200 x-auth-token: 4792331e-44c2-4285-a9d1-ebabf0e72251 Content-Type: text/html;charset=UTF-8 Content-Length: 75 Date: Mon, 09 Jan 2017 10:14:00 GMT 8e107efb-bf1e-4a55-b896-c97f629c8e40 : 4792331e-44c2-4285-a9d1-ebabf0e72251 |
使用cookie,會看到如下信息
1
2
3
4
5
6
|
-- response -- 200 Set-Cookie: SESSION=4792331e-44c2-4285-a9d1-ebabf0e72251;path=/;HttpOnly Content-Type: text/html;charset=UTF-8 Content-Length: 75 Date: Mon, 09 Jan 2017 10:47:37 GMT |
測試
在controller中增加如下代碼
1
2
3
4
5
6
7
8
9
10
|
@GetMapping ( "/" ) public String uid(HttpServletRequest request) { HttpSession session = request.getSession(); UUID uid = (UUID) session.getAttribute( "uid" ); if (uid == null ) { uid = UUID.randomUUID(); } session.setAttribute( "uid" , uid); return uid.toString() + " : " + session.getId(); } |
啟動服務,在chrome瀏覽器輸入 http://127.0.0.1:8080/,得到sessionId
1
|
fbfae849-1d49-4301-b963-573048e763e7 |
在redis中可以看到如下信息
1) "spring:session:xxxx:sessions:fbfae849-1d49-4301-b963-573048e763e7"
2) "spring:session:xxxx:expirations:1483958700000"
3) "spring:session:xxxx:sessions:expires:fbfae849-1d49-4301-b963-573048e763e7"
打開火狐的HttpRequester,使用chrome獲取的sessionId點擊Get,可以看到如下輸出
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/zl18310999566/article/details/54290994