使用idea,springboot,springsession,redis實現分布式微服務的session 共用

來源:互聯網
上載者:User

標籤:project   容器   path   filter過濾器   localhost   tco   port   seconds   extend   

本次開發環境:idea2016.3.4 +jdk1.8+maven3.3.9+redis+springboot+jedis

 本文中的項目使用Maven來管理項目依賴,使用Spring Session和Redis的組合來代替原有的HttpSession實現Session在不同項目之間的共用

項目結構:

構建Spring Boot 

pom檔案如下

<modelVersion>4.0.0</modelVersion>

<groupId>com.cky.sessionshare</groupId>
<artifactId>spring-session-share</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>

<!-- spring boot 基本環境 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>

<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--spring boot web應用基本環境配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Application.java

實現Spring Boot的啟動main函數

@SpringBootApplication
public class Application {
// 自動設定Spring架構
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
測試測試代碼

建立一個類HelloWorldController用於測試

@RestController
public class HelloWorldController {

@RequestMapping("/index/{name}")
@ResponseBody
public String index(@PathVariable String name) {

if (null == name) {
name = "boy";
}

return "hello world " + name;
}
}
運行Application.java來啟動Spring Boot,訪問”http://localhost:8080/index/陳冠希”出現以下頁面,說明Spring Boot部署成功

加入Spring Session架構pom.xml

引入Spring Session和Redis需要的依賴

 <!--spring boot 與redis應用基本環境配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

<!--spring session 與redis應用基本環境配置,需要開啟redis後才可以使用,不然啟動Spring boot會報錯 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
</dependencies>

Spring Session配置

建立一個Spring配置,用於建立一個支援Spring Session的Servlet Filter來代替原有的HttpSession的實現。

@EnableRedisHttpSession(maxInactiveIntervalInSeconds= 1800)
public class SessionConfig {

@Value("${redis.hostname:localhost}")
String HostName;

@Value("${redis.port:6379}")
int Port;
@Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory connection = new JedisConnectionFactory();
return connection;
}
}

JedisConnectionFactory

預設串連連接埠:6379 
預設串連地址:localhost 
需要修改則可以使用JedisConnectionFactory的setPort()方法和setHostName()方法來修改預設的連接埠和串連地址

這裡可以引入設定檔使Redis的配置更加靈活建立設定檔application.properties

 

redis.homename = localhost
redis.port = 6379

在類SessionConfig中引入設定檔的值

修改後的SessionConfig類代碼如下:

@EnableRedisHttpSession(maxInactiveIntervalInSeconds= 1800)
public class SessionConfig {

@Value("${redis.hostname:localhost}")
String HostName;

@Value("${redis.port:6379}")
int Port;
@Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory connection = new JedisConnectionFactory();
connection.setPort(Port);
connection.setHostName(HostName);

return connection;
}
}
載入Spring Session配置
載入Spring Session配置,使得Servlet容器在每一次請求時都使用我們的springSessionRepositoryFilter過濾器。
public class SessionInitializer  extends AbstractHttpSessionApplicationInitializer{
public SessionInitializer (){
super(SessionConfig.class);
}

}
測試

以上已經完成了Spring Boot + Spring Session +Redis的配置 
測試是否可以在不同的容器(e.g. Tomcat),不同的項目中都訪問到同一個Session

運行Redis拷貝一個項目

項目結構與主專案相同

 

修改容器連接埠

修改Spring Boot中內建Tomcat的介面 
在application.properties中加入server.port=8090

實現Session的讀寫添加測試方法主專案

在主專案中的類HelloWorldController中添加一個TestSession方法 
用於儲存和讀取Session 
修改後的代碼如下

@RestController
public class HelloWorldController {

@RequestMapping("/index/{name}")
@ResponseBody
public String index(@PathVariable String name) {

if (null == name) {
name = "boy";
}

return "hello world " + name;
}

@RequestMapping("/tsession/{age}")
@ResponseBody
public String TestSession(HttpServletRequest req, HttpServletResponse resp, @PathVariable String age){
req.getSession().setAttribute("age", age);
String a = (String) req.getSession().getAttribute("age");

return a;
}
}
測試專案

為了測試是否可以讀取Session,測試專案的Session不做儲存操作 
修改測試專案的HelloWorldController類中的TestSession方法 
修改後的代碼為

@RestController
public class WelcomeController {

@RequestMapping("/welcome/{name}")
@ResponseBody
public String index(@PathVariable String name) {

if (null == name) {
name = "edison";
}

return "welcome " + name;
}

@RequestMapping("/tsession/{age}")
@ResponseBody
public String TestSession(HttpServletRequest req, HttpServletResponse resp, @PathVariable String age){
String a = (String) req.getSession().getAttribute("age");
return a;
}
}
開始測試

分別運行主專案和測試專案的Application.java檔案

驗證

先登入”http://localhost:8080/tsession/88“儲存Session資訊,結果如所示: 

再登入”http://localhost:8090/tsession/88“,測試是否可以讀取到之前的資訊:若結果如,這表示測試成功:

 

 

 這時用redis desktop manager查看redis探索資料

 

用Google查看剛才傳遞的給服務的cookie

最佳化

若每一次建立項目都要寫一次的Session的配置,那麼代碼的複用性太差,那麼不如把Session的配置單獨打包出來,之後只需要在項目中加入一個依賴就可以實現Spring Session的功能。

項目結構

 

 

 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/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.springboot.sessionshare</groupId>
<artifactId>springbootsessionshare</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>

<name>A Camel Route</name>

<!-- spring boot 基本環境 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>

<dependencies>
<!--spring boot web應用基本環境配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--spring boot 與redis應用基本環境配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

<!--spring session 與redis應用基本環境配置,需要開啟redis後才可以使用,不然啟動Spring boot會報錯 -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>

</dependencies>

</project>
配置類SessionConfig和載入類SessionInitializer的代碼與之前沒有變化
Maven install

由於項目依賴是由Maven來管理的,那麼使用Maven install將項目安裝到Maven的本地倉庫當中 

測試建立測試專案pom.xml

先擷取去需要依賴的項目的Maven位置,位置在安裝到本地倉庫的項目的pom.xml檔案中擷取

將位置加入到測試專案中 

設定連接埠

server.port=8050

其他測試檔案

Application.java檔案和HelloWorldController檔案代碼與之前的一致,以下就不貼出代碼了

 

 

開始測試

運行Redis-運行測試專案中的Application.java檔案-訪問”http://localhost:8050/tsession/100” 

若效果與效果一致,則建立成功 

 

 

 

 





 

 

使用idea,springboot,springsession,redis實現分布式微服務的session 共用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.