解决session共享问题

方法一

使用Nginx让它绑定ip(没有共享所以就没有共享问题了)

配置Nginx

upstream backserver { 
	ip_hash;
	server localhost:8080; 
	server localhost:8081; 
}
server {
	listen       80;
	server_name  www.wish.com;
	location / {
		proxy_pass http://backserver;
		index index.html index.htm;
					
        }
}

  

这样就可以,但是还是没用根本的解决问题,所以使用下面这个

方法二:

使用spring session+redis的方法解决session共享问题

第一步:导入依赖

   <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <!-- spring-boot-starter-web是为我们提供了包括mvc,aop等需要的一些jar -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- 因为我们已经配置了 parent 中的version 所以这里不需要指定version了 -->
        </dependency>
        <!--spring boot 与redis应用基本环境配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency> <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
</dependency>

  

注意:spring session的版本最高是1.3.5.RELEASE

第二步:配置application.properties

server.port=8081

spring.redis.password=redis

  

注意:redis的密码一定要填写对

第三步:写一个controller进行测试

package com.wish.session;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RestController
public class SessionController {
    //存放Session值
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        System.out.println("123456");
        request.getSession().setAttribute("username","zhangsan");
        return "success";
    }

    //获取Session值
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        System.out.println("123456");
        return (String)request.getSession().getAttribute("username");
    }
}

  

测试结果:

页面

redis:会生成一个spring的文件(用于存储session)

原文地址:https://www.cnblogs.com/wishsaber/p/12299982.html