方法一
使用Nginx讓它綁定ip(沒有共享所以就沒有共享問題了)
配置Nginx
upstream backserver {
ip_hash;
server localhost:8080;
server localhost:8081;
}
server {
listen 80;
server_name www.wish.com;
location / {
proxy_pass http://backserver;
index index.html index.htm;
}
}
這樣就可以,但是還是沒用根本的解決問題,所以使用下面這個
方法二:
使用spring session+redis的方法解決session共享問題
第一步:導入依賴
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<!-- spring-boot-starter-web是為我們提供了包括mvc,aop等需要的一些jar -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 因為我們已經配置了 parent 中的version 所以這里不需要指定version了 -->
</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>
注意:spring session的版本最高是1.3.5.RELEASE
第二步:配置application.properties
server.port=8081 spring.redis.password=redis
注意:redis的密碼一定要填寫對
第三步:寫一個controller進行測試
package com.wish.session;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
public class SessionController {
//存放Session值
@RequestMapping("/setSession")
public String setSession(HttpServletRequest request){
System.out.println("123456");
request.getSession().setAttribute("username","zhangsan");
return "success";
}
//獲取Session值
@RequestMapping("/getSession")
public String getSession(HttpServletRequest request){
System.out.println("123456");
return (String)request.getSession().getAttribute("username");
}
}
測試結果:
頁面


redis:會生成一個spring的文件(用於存儲session)

