环境

centos7、 jdk1.8、nginx、redis、springboot 1.5.8.RELEASE

session共享

  1. 添加spring session和redis依赖

    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
    	<groupId>org.springframework.session</groupId>
    	<artifactId>spring-session</artifactId>
    </dependency>
    
  2. application.properties配置

# session 存入 redis
spring.session.store-type=redis

# redis config
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=20000
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0

此处redis密码设置为123456

  1. 测试代码

    @RequestMapping("user")
    @RestController
    public class UserController {
    
        @GetMapping("getSessionId")
        public String getSessionId(HttpServletRequest request) {
            String sessionId = request.getSession().getId();
            System.out.println(sessionId);
            return sessionId;
        }
    }
    

    项目完整代码下载地址:[springboot-session-redis]: https://github.com/linj6/springboot-learn/tree/master/springboot-session-redis

负载均衡

nginx.conf配置

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    
    keepalive_timeout  65;

    upstream springboot-session-redis {
        server 127.0.0.1:8081;
        server 127.0.0.1:8082;
        server 127.0.0.1:8083;
    }

    server {
        listen       80;
        server_name  localhost;

        location / {
            proxy_pass http://springboot-session-redis;
            proxy_set_header Host                $host;
			# 此配置使得服务端可以获取客户端真实ip
            proxy_set_header X-Real-IP           $remote_addr;
            proxy_set_header X-Forwarded-For     $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto   $scheme;
            proxy_redirect                       off;
        }
    }
}

测试

  1. 启动redis

    systemctl start redis
    
  2. 启动三个应用服务

    使用maven打包成jar包后 ,在后台运行三个服务,端口分别为8081、8082、8083,日志分别输出到nohup.out、nohup2.out、nohup3.out

    nohup java -jar springboot-session-redis-0.0.1-SNAPSHOT.jar --server.port=8081 > nohup.out &
    
    nohup java -jar springboot-session-redis-0.0.1-SNAPSHOT.jar --server.port=8082 > nohup2.out &
    
    nohup java -jar springboot-session-redis-0.0.1-SNAPSHOT.jar --server.port=8083 > nohup3.out &
    
  3. 启动nginx

  4. 访问http://ip/user/getSessionId

    1. 页面显示sessionId的值

    ​ nginx默认负载均衡策略是采用轮询,此处启动了三个服务,所以访问三次该网址,查看三个服务的日志,会发现每个服务处理了一次请求。

    如下图:

    nohup.out

    nohup2.out

    nohup3.out

    从上图可知三次输出的sessionId的值也是一样的,所以实现了session共享,也通过nginx实现了负载均衡。

  5. 查看redis存储的值

可以看到生成了三个与spring session相关的key