Session共享解决方案

使用nginx做的负载均衡添加一个ip_hash配置

一.开两个Tomcat写测试程序

@WebServlet("/nginxSessionServlet")
public class NginxSessionServlet  extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("当前使用端口:"+req.getLocalPort());
        String action = req.getParameter("action");
        if (action.equals("setSession")){
            req.getSession().setAttribute("username","wnwn");
            resp.getWriter().write("success");
        }else if (action.equals("getSession")){
            resp.getWriter().write((String)req.getSession().getAttribute("username"));
        }
    }
}

二.配置配置nginx.conf文件

 upstream myserver{
         ip_hash;
         server 127.0.0.1:8080;
         server 127.0.0.1:8081;
    }
    server{
        listen       81;
        server_name  www.bproject.com;
        location / {
            root   html;
            proxy_pass  http://myserver;
            index  index.html index.htm;
        }
    }

三.启动nginx,并访问

 当第一次请求时,负载均衡将请求转发到8080端口上,因为配置了ip_hash,所以每次请求都会转发到8080端口上,相当于把请求和8080端口粘到一块了。

利用spring-session+Redis

一:创建一个springboot工程,启动两次,端口分别为8082和8083导入依赖

 <!--spring boot 与redis应用基本环境配置 -->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-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>

二.测试

@RestController
public class SessionController {

    @RequestMapping("/setSession")
    public String setSession(HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.getSession().setAttribute("username","wang");
        return "success";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request,HttpServletResponse response){
        String username = (String) request.getSession().getAttribute("username");
        return username;
    }
}

三.配置application.properties文件

server.port=8082
#server.port=8083

#redis配置
spring.redis.password: wang2003

四.启动测试

页面返回success时,就成功将数据添加到Redis缓存中了

原文地址:https://www.cnblogs.com/danxun/p/12300048.html