springboot使用redis保存session,实现共享session集群
1.pom.xml
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2.开启@EnableRedisHttpSession
@SpringBootApplication
@EnableRedisHttpSession
public class SessionRedisClusterApplication {
public static void main(String[] args) {
SpringApplication.run(SessionRedisClusterApplication.class,args);
}
}
@RestController
@Slf4j
public class MainController {
@Value("${server.port}")
private Integer port;
@GetMapping("login")
public String login(String username, HttpSession session){
session.setAttribute("username",username);
log.info("port="+port);
return "login port="+port;
}
@GetMapping("test")
public String test(HttpSession session){
log.info("port="+port);
return "login port="+port+" username="+session.getAttribute("username");
}
}
3.nginx负载配置
upstream backendtest {
server 127.0.0.1:8084;
server 127.0.0.1:8085;
}
server {
listen 80;
server_name www.test2.com;
location / {
proxy_pass http://backendtest;
proxy_cookie_path / /;
proxy_set_header Host $host;
proxy_set_header Remote_Addr $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Vary "Accept-Encoding,User-Agent";
}
}
访问:http://www.test2.com/login?username=dkn
访问:http://www.test2.com/test
轮询返回数据:login port=8084 username=dkn 和 login port=8085 username=dkn