SpringBoot Session共享

贺景铄
2023-12-01

Session共享

  当一请求到达 Nginx务器后先进行请求分发,假设请求被real server1处理了,real server 1在处理请求时,无论是存储Session还是读取Session都去操作Session务器而不是操作自身内存中 Session。real server 理请求时如此,这样就可以实现 Session 享了。

1、pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

2、application.yml

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        max-wait: -1ms
        min-idle: 0
server:
  port: 8081

3、请求控制层

@RestController
public class SessionController {

    @Value("${server.port}")
    String port;

    @PostMapping("/save")
    public String saveName(String name, HttpSession session) {
        session.setAttribute("name", name);
        return port;
    }

    @GetMapping("/get")
    public String getName(HttpSession session) {
        String name = session.getAttribute("name").toString();
        return port + ":" + name;
    }
}

分别将程序启动在8080和8081端口

4、配置Nginx

  • nginx.conf配置如下

    upstream sang.com {
    		server 127.0.0.1:8080 weight=1;
    		server 127.0.0.1:8081 weight=1;
    	}
    	server {
    		listen 83;
    		server_name localhost;
    		location / {
    			proxy_pass http://sang.com;
    			proxy_redirect default;
    		}
    	}
    

启动nginx,访问Post -> http://127.0.0.1:83/save?name=测试,保存Session
然后访问 Get -> http://127.0.0.1:83/get,这个可以看出返回的端口在8080和8081之间切换

 类似资料: