1. 程式人生 > >spring-boot 整合spring-session redis

spring-boot 整合spring-session redis

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 Session實現新一代的Session管理,更多內容可以點選閱讀。

Spring-Boot整合Spring session並存入redis

新增maven依賴

redis的相關依賴可以看之前的內容,這裡需要增加如下依賴。

<dependency>
     <groupId>org.springframework.session</groupId>
     <artifactId>spring-session</artifactId>
</dependency>

Java程式碼實現

增加HttpSessionConfig。

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 資訊。

    @Bean
    public HttpSessionStrategy httpSessionStrategy() {
        return new CookieHttpSessionStrategy();
    }
使用HTTP的頭,會看到如下資訊
-- 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,會看到如下資訊

 -- 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中增加如下程式碼

    @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

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,可以看到如下輸出

參看連結