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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM