Session:在計算機中,尤其是在網路應用中,稱為“會話控制”。Session 物件儲存特定使用者會話所需的屬性及配置資訊。這樣,當使用者在應用程式的 Web 頁之間跳轉時,儲存在 Session 物件中的變數將不會丟失,而是在整個使用者會話中一直存在下去。當使用者請求來自應用程式的 Web 頁時,如果該使用者還沒有會話,則 Web 伺服器將自動建立一個 Session 物件。當會話過期或被放棄後,伺服器將終止該會話。Session 物件最常見的一個用法就是儲存使用者的首選項。
Session管理
本文主要描述在 Spring Security
下 Session
的以下三種管理,
Session
超時時間Session
的併發策略- 叢集環境
Session
處理
Session超時
application.yml
配置超時時間
server:
port: 80
session:
timeout: 60
複製程式碼
http.
......
.sessionManagement()
.invalidSessionUrl("/session/invalid")//session失效跳轉的連結
.....
複製程式碼
Cotroller
中/session/invalid
@GetMapping("/session/invalid")
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public Result<String> sessionInvalid() {
return ResultUtil.error(HttpStatus.UNAUTHORIZED.value(), "session失效");
}
複製程式碼

Session的併發策略
http.
......
.maximumSessions(1)//最大session併發數量1
.maxSessionsPreventsLogin(false)//false之後登入踢掉之前登入,true則不允許之後登入
.expiredSessionStrategy(new MerryyounExpiredSessionStrategy())//登入被踢掉時的自定義操作
.....
複製程式碼
MerryyounExpiredSessionStrategy
@Slf4j
public class MerryyounExpiredSessionStrategy implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent eventØ) throws IOException, ServletException {
eventØ.getResponse().setContentType("application/json;charset=UTF-8");
eventØ.getResponse().getWriter().write("併發登入!");
}
}
複製程式碼

當maxSessionsPreventsLogin(true)
可參考:Spring-Security和security-oauth2
叢集環境Session處理
- 新增spring-session-data-redis依賴
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
複製程式碼
- 配置Spring-session儲存策略
spring:
redis:
host: localhost
port: 6379
session:
store-type: redis
複製程式碼
- 測試
8080
和8081
埠分別啟動專案
java -jar spring-security.jar --server.port=8080
java -jar spring-security.jar --server.port=8081
複製程式碼
效果如下:

關於更多Spring Session可參考:程式猿DD
程式碼下載
從我的 github 中下載,github.com/longfeizhen…