spring-session与redis实现session共享

一.准备

  1. 两个不同端口号的输出request.getLocalPort() + " ---> " + request.getSession(true).getId()的简单Springboot程序
  2. nginx

二.Springboot中使用spring-session以及redis共享session

2.1.POM配置

 1 <dependencies>
 2     <dependency>
 3         <groupId>org.springframework.bootgroupId>
 4         <artifactId>spring-boot-starter-webartifactId>
 5     dependency>
 6     <dependency>
 7         <groupId>org.springframework.sessiongroupId>
 8         <artifactId>spring-session-data-redisartifactId>
 9     dependency>
10     <dependency>
11         <groupId>redis.clientsgroupId>
12         <artifactId>jedisartifactId>
13         <version>2.9.0version>
14     dependency>
15 dependencies>

2.2.application.properties配置

1 # Session store type.
2 spring.session.store-type=redis
3 # Namespace for keys used to store sessions.
4 spring.session.redis.namespace=spring:session
5 # Redis server host.
6 spring.redis.host=localhost
7 # Redis server port.
8 spring.redis.port=6379

2.3.一个简单的REST接口(返回request.getLocalPort()和request.getSession(true).getId())

1 @RestController
2 public class TestSessionShare {
3 
4     @GetMapping("session")
5     public String getSession(HttpServletRequest request) {
6         return request.getLocalPort() + " ---> " + request.getSession(true).getId();
7     }
8 
9 }

2.4.package上面的Springboot程序

2.5.启动两个不同端口号的节点

1 java -jar demo.jar --server.port=9988
2 java -jar demo.jar --server.port=9999

三.Nginx

3.1.配置nginx.conf

 1 http {
 2 
 3     ......
 4     
 5     upstream sessionShare {
 6         server 127.0.0.1:9988 weight=1;
 7         server 127.0.0.1:9999 weight=1;
 8     }
 9     
10     server {
11         listen       80;
12         server_name  localhost;
13 
14         location / {
15             proxy_pass http://sessionShare;
16         }
17     }
18     
19     ......
20     
21 }

3.2.启动nginx验证session是否共享

启动nginx,打开浏览器不停刷新http://localhost/session
结果如下:

转载于:https://www.cnblogs.com/yhcjhun/p/10896930.html

你可能感兴趣的:(spring-session与redis实现session共享)