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