一、什么是负载均衡
二、负载均衡策略
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端输出