美文网首页
nginx+tomcat负载均衡和session复制

nginx+tomcat负载均衡和session复制

作者: 无至 | 来源:发表于2018-08-22 17:50 被阅读8次

1、安装nginx

2、修改nginx/conf/nginx.conf文件,支持负载均衡


worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    #负载均衡模块节点+tomcat服务
    upstream test{
        server localhost:8080 weight=1;
        server localhost:8081 weight=1;
    }

    server {
        listen       80;
        server_name  localhost;


        location / {

            #proxy_pass配置为:http:// + upstream名称
            proxy_pass  http://test;

            #添加如下3个配置后,当一台server宕机,切换速度会很快,此时配置是1秒  
            proxy_connect_timeout   1;   
            proxy_send_timeout      1;  
            proxy_read_timeout      1;              
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

}


3、tomcat配置

3.1、下载tomcat,解压、复制、重命名为tomcat6-8080、tomcat6-8081两个文件夹。
3.2、修改每个tomcat目录下的server.xml文件
<!-- 端口配置 -->
<!-- 关闭指令端口 -->
<Server port="8005" shutdown="SHUTDOWN">
<Server port="8006" shutdown="SHUTDOWN">

<!--请求处理端口,8080为http请求处理端口,8443位https请求处理端口-->
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
<Connector port="8081" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

<!--接收AJP协议的处理端口-->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<Connector port="8010" protocol="AJP/1.3" redirectPort="8443" />


<!--session复制配置-->
<!--取消Cluster节点的注释-->
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
<!--在Engine节点中增加jvmRoute,多个tomcat保持相同值-->
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">

4、部署项目

4.1、新建一个javaweb工程,命名为test,包含web.xml和index.jsp即可,部署至两个tomcat中
4.1、web.xml中添加<distributable/>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:javaee="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
    id="WebApp_ID" version="2.4">
    <distributable/>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

4.2、 index.jsp
<%@ page pageEncoding="UTF-8"%>

<!DOCTYPE HTML>
<html>
<head>
<title>sessionId</title>
</head>
<body>
    
    tomcat-8080 sessionId : <%=session.getId()%>

</body>
</html>

5、测试

多次访问http://localhost/test,结果如下:

tomcat-8080 sessionId : A486C4A2355074B0C56604863C487A7F.jvm1 
tomcat-8081 sessionId : A486C4A2355074B0C56604863C487A7F.jvm1 

相关文章

网友评论

      本文标题:nginx+tomcat负载均衡和session复制

      本文链接:https://www.haomeiwen.com/subject/womyiftx.html