Tomcat集群,可以提高服务的性能,并发能力以及高可用性。提供项目架构的横向扩展能力。
那么Tomcat集群的实现原理是?通过nginx负载均衡进行请求转发。
Tomcat单机部署多应用
Linux下:
在/etc/profilexia下增加tomcat环境变量:
export CATALINA_BASE=/User/haozi/tomcat1
export CATALINA_HOME=/User/haozi/tomcat1
export TOMCAT_HOME=/User/haozi/tomcat1
export CATALINA_2_BASE=/User/haozi/tomcat2
export CATALINA_2_HOME=/User/haozi/tomcat2
export TOMCAT_2_HOME=/User/haozi/tomcat2
第一个tomcat不变,打开第二个tomcat目录bin/catalina.sh
找到 #OS specific support. $var_must_be set to either true or false.在下面新增:
export CATALINA_BASE=$CATALINA_2_BASE
export CATALINA_HOME=$CATALINA_2_HOME
然后打开/conf/server.xml,修改三个端口:
Server port修改为9005,Connector port改为9080,Connect port 后面带有protocol的端口改为9009
然后分别启动。
windows下:
增加环境变量:
CATALINA_BASE=/User/haozi/tomcat1
CATALINA_HOME=/User/haozi/tomcat1
TOMCAT_HOME=/User/haozi/tomcat1
CATALINA_2_BASE=/User/haozi/tomcat2
CATALINA_2_HOME=/User/haozi/tomcat2
TOMCAT_2_HOME=/User/haozi/tomcat2
第一个都不变,打开第二个/bin/catalina.bat和startup.bat,把两个中的CATALINA_BASE->CATALINA_2_BASE、CATALINA_HOME->CATALINA_2_HOME
/conf/server.xml修改三个端口,linux的一致。
启动两个tomcat。
Tomcat单机部署多应用
多机部署要比单机部署简单很多,如果一个及其部署一个实例,配置之类都不需要修改。保证机器之间可以相互通信即可。
Nginx负载均衡
配置:
轮询(默认):优点:实现简单,缺点:不考虑每个服务器的处理能力。配置方法:
upstream www.haozirou.com{
server www.haozirou.com:8080;
server www.haozirou.com:9080;
}
权重:优点:考虑了每台服务器处理能力的不同,配置方法:
upstream www.haozirou.com{
server www.haozirou.com:8080 weight=15;
server www.haozirou.com:9080 weight=10;
}
ip hash:就是把请求的ip进行hash,然后分配到指定的服务器上。优点:能实现同一个用户访问同一台服务器。缺点:根据ip hash不一定平均。配置方法:
upstream www.haozirou.com{
ip_hash;
server www.haozirou.com:8080;
server www.haozirou.com:9080;
}
url hash(第三方,需要装nginx插件) :优点:能实现同一个服务访问同一个服务器。缺点:根据url hash分配请求会不平均,请求频繁的url会请求到同一个服务器上。配置方法:
upstream www.haozirou.com{
server www.haozirou.com:8080;
server www.haozirou.com:9080;
hash $request_uri;
}
fail(第三方):按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream www.haozirou.com{
server www.haozirou.com:8080;
server www.haozirou.com:9080;
fair;
}
负载均衡配置的扩展点
upstream www.haozirou.com{
ip_hash;
server www.haozirou.com:8080 down;
server www.haozirou.com:9080 weight=2;
server www.haozirou.com:10080 backup;
}
down:表示当前的server暂时不参与负载。
weight:默认为1,值越大,负载的权重越大。
backup:其他所有的非backup机器down或者忙的时候,请求处理backup机器。
Nginx+Tomcat搭建集群
启动tomcat
修改系统host(浏览器所在机器的host):
linux:sudo vim /etc/hosts,增加127.0.0.1 www.haozirou.com
windows:C:\Windows\System32\drivers\etc\hosts,增加127.0.0.1 www.haozirou.com
接下来ping www.haozirou.com看能不能通即可。
编辑nginx下的conf/nginx.conf配置文件,在http节点下增加:include vhost/*.conf;这样做的目的是为了增加tomcat集群的负载均衡配置,并把域名配置文件分开,方便后期管理。
在conf目录下建文件夹vhost,增加haozirou.conf配置文件:
upstream www.haozirou.com{
server www.haozirou.com:8080 weight=15;
server www.haozirou.com:9080 weight=10;
}
server{
listener 80;
autoindex on;
server_name haozirou.com www.haozirou.com;
access_log /usr/local/nginx/logs/access.log combined;
index index.html index.htm index.jsp index.php;
location / {
proxy_pass http://www.haozirou.com;
add_header Access-Control_allow_origin *;
}
}
启动nginx即可。