Spring Session - 使用Redis存儲HttpSession例子


目的

使用Redis存儲管理HttpSession;

添加pom.xml

該工程基於Spring Boot,同時我們將使用Spring IO Platform來維護依賴版本號;

引入的依賴有spring-session、spring-boot-starter-web、spring-boot-starter-redis,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.spring.platform</groupId>
                <artifactId>platform-bom</artifactId>
                <version>Athens-SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.4.3.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- Additional lines to be added here... -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.3.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

配置Spring Session

配置比較簡單,主要是添加@EnableRedisHttpSession注解即可,該注解會創建一個名字叫springSessionRepositoryFilter的Spring Bean,其實就是一個Filter,這個Filter負責用Spring Session來替換原先的默認HttpSession實現,在這個例子中,Spring Session是用Redis來實現的。

import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@EnableRedisHttpSession
public class HttpSessionConfig {
    
}

操作HttpSession

這里我們將實現兩個操作,一個是往Session中寫入數據,另一個是查詢數據,如下所示:

@RestController
public class Example {

    @RequestMapping("/set")
    String set(HttpServletRequest req) {
        req.getSession().setAttribute("testKey", "testValue");
        return "設置session:testKey=testValue";
    }

    @RequestMapping("/query")
    String query(HttpServletRequest req) {
        Object value = req.getSession().getAttribute("testKey");
        return "查詢Session:\"testKey\"=" + value;
    }

}

編寫main方法

編寫main方法,使用@SpringBootApplication注解標注,如果查看該注解源碼的話,會發現相當於添加了@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan等注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class APP {
       public static void main(String[] args) throws Exception {
            SpringApplication.run(APP.class, args);
        }
}

運行程序,測試驗證

1、本地啟動redis服務;

2、打開redis客戶端,輸入flushall清空緩存;

3、瀏覽器輸入http://localhost:8080/set,設置Session

redis客戶端輸入keys *命令, 可以發現redis中確實有數據插入:

4、瀏覽器輸入http://localhost:8080/query,查詢Session

5、清空redis緩存,瀏覽器輸入http://localhost:8080/query,再次查詢Session

發現HttpSession中已經無數據。

 

最后,如果查看瀏覽器的cookie的話,會發現有一個name為“SESSION”的cookie,其值為redis中spring session key的一部分。

 

另外,還可以在redis客戶端輸入HGETALL來查看spring session具體的值,如下:

結論:以上測試結果全部符合預期,HttpSession的實現成功被Spring Session替換,操作HttpSession等同於操作redis中的數據。

工程源碼參考

https://github.com/peterchenhdu/spring-session-example

參考資料

http://docs.spring.io/spring-session/docs/1.3.1.BUILD-SNAPSHOT/reference/html5/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM