首先pom.xml引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
控制器里写方法:
@RestController
@RequestMapping(value = "/api/user")
public class LoginController {
@RequestMapping(value = "/showPort")
public String showPort (HttpServletRequest request) {
return request.getLocalPort() + "";
}
@RequestMapping(value = "/saveSession")
public String saveSession (HttpServletRequest request) {
request.getSession().setAttribute("userName", "admin");
return request.getLocalPort() + "—" + request.getSession().getId();
}
@RequestMapping(value = "/getSession")
public String getSession (HttpServletRequest request) {
String userName = (String) request.getSession().getAttribute("userName");
return request.getLocalPort() + "userName:" + userName;
}
}
然后把项目复制出来一份,改个名,修改application.properties配置,两个不同端口
server.port=9999
server.port=9998
配置nginx负载均衡,启动nginx
upstream transformers {
server 127.0.0.1:9999;
server 127.0.0.1:9998;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://transformers;
}
}
然后是很关键的一步:启动你的两个项目,看下运行效果
用9998端口存session,9999端口获取session
GameOver~bingo