共计 2834 个字符,预计需要花费 8 分钟才能阅读完成。
一、什么是负载均衡
二、负载均衡策略
1、轮询(默认)
2、指定权重
3、IP 绑定 ip_hash
4、fair(第三方)
5、url_hash(第三方)
三、轮询(默认)
1、模拟集群
设置两个 Tomcat 同时访问一个 servlet
import Javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(“/NginxServlet”)
public class NginxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(“Nginx 负载均衡!”);
System.out.println(“ 当前访问端口:”+request.getServerPort());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
2、修改 nginx.conf 文件
3、启动 Nginx 和 Tomcat
4、访问 www.znzn.com/NginxServlet 2 次
5、控制台效果 80 和 81 端口输出一次
四、设置权重
1、模拟集群
设置两个 Tomcat 同时访问一个 servlet
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(“/NginxServlet”)
public class NginxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(“Nginx 负载均衡!”);
System.out.println(“ 当前访问端口:”+request.getServerPort());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
2、修改 nginx.conf 文件
3、启动 Nginx 和 Tomcat
4、访问 www.znzn.com/NginxServlet 5 次
5、控制台效果(底层算法默认先走一遍轮询)80 输出 2 次 81 输出 1 次
五、IP 绑定
1、模拟集群
设置两个 Tomcat 同时访问一个 servlet
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(“/NginxServlet”)
public class NginxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(“Nginx 负载均衡!”);
System.out.println(“ 当前访问端口:”+request.getServerPort());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
2、修改 nginx.conf 文件
3、启动 Nginx 和 Tomcat
4、访问 www.znzn.com/NginxServlet
5、控制台效果 无论访问几次都只会在 80 端输出