zoukankan      html  css  js  c++  java
  • Nginx绑定IP,解决session共享

    1.Nginx通过负载均衡IP地址固定绑定,解决Session共享
               upstream note.java.itcast.cn{
            ip_hash;
              server localhost:8080  weight=1;
              server localhost:8081  weight=1;
          }
                
                server {
                    listen       80;
                    server_name  note.java.itcast.cn;

                    #charset koi8-r;

                    #access_log  logs/host.access.log  main;

                    location / {
                        
                        proxy_pass http://note.java.itcast.cn;
                        index index.html index.htm;
                        
                    }
                }

    只需要在 upstream添加一个 ip_hash;属性,

    相同的请求就会一直请求第一次绑定的这个IP

    实现方式

    新建一个servlet用于接收请求

    @WebServlet("/NginxSessionServlet")
    public class NginxSessionServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("当前请求端口:"+req.getLocalPort());
            String action=req.getParameter("action");
            //向Session中存放一个数据
            if(action.equals("setSession")){
                req.getSession().setAttribute("username","zhangsan");
            }else if(action.equals("getSession")){
                resp.getWriter().write((String)req.getSession().getAttribute("username"));
            }
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }

    实现效果

    无论访问多少次,都只会请求8080端口

    但是这种方式不推荐使用,因为其他的服务器就一直不会使用,达不到负载均衡的目的

    推荐使用Spring-session+Redis的方式实现

    https://www.cnblogs.com/chx9832/p/12298760.html

  • 相关阅读:
    《构建之法》第四章读后感
    复利计算-单元测试
    hadoop 不同URLTitle文件提取关联URL
    全角转半角-半角转全角
    leetcode unique binary search Tree
    leetcode validBST
    leetcode -- Flatten Binary Tree to Linked List
    堆排序
    比较字符串总结:如果计算两个字符串的相似度或者距离
    leetcode Populating Next Right Pointers in Each Node
  • 原文地址:https://www.cnblogs.com/chx9832/p/12298769.html
Copyright © 2011-2022 走看看