Nginx+Tomcat配置集羣session共享

tomcat自帶session共享功能 不必非集成第三方軟件 只需配置即可 http://tomcat.apache.org/tomcat-8.5-doc/cluster-howto.html

爲什麼選擇Nginx?

Nginx 是一個很強大的高性能Web和反向代理服務器,它具有很多非常優越的特性:
在連接高併發的情況下,Nginx是Apache服務器不錯的替代品:Nginx在美國是做虛擬主機生意的老闆們經常選擇的軟件平臺之一。能夠支持高達 50,000 個併發連接數的響應,感謝Nginx爲我們選擇了 epoll and kqueue作爲開發模型。

配置結構圖

1、下載地址

http://nginx.org/en/download.html ,這裏我們推薦下載穩定版(stable versions),本文采用nginx/Windows-1.12.0。

2、目錄結構

Nginx-
| conf 配置目錄
| contrib
| docs 文檔目錄
| logs 日誌目錄
| temp 臨時文件目錄
| html 靜態頁面目錄
|_ nginx.exe 主程序
window下安裝Nginx極其簡單,解壓縮到一個無空格的英文目錄即可(個人習慣,擔心中文出問題),雙擊nginx啓動,這裏我安裝到:D:\nginx目錄,下面涉及到的tomcat也安裝在此目錄。



Nginx  命令


start nginx
nginx -s stop
nginx -s quit

3、nginx.conf配置

Nginx配置文件默認在conf目錄,主要配置文件爲nginx.conf

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

	upstream suroot{
        server 127.0.0.1:8090 max_fails=2 fail_timeout=30s;
        server 127.0.0.1:9091 max_fails=2 fail_timeout=30s;
    }
	
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
			root   html;
			index  index.html index.htm index.jsp login.jsp; #定義首頁索引文件的名稱
			proxy_pass http://suroot/;#請求轉向suroot定義的服務器列表
			#以下是一些反向代理的配置可刪除.
			proxy_redirect off;
			proxy_set_header   Host $host;
			proxy_set_header   X-Real-IP $remote_addr;
			proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
			client_max_body_size   10m;#允許客戶端請求的最大單文件字節數
			client_body_buffer_size   128k;#緩衝區代理緩衝用戶端請求的最大字節數,
			proxy_connect_timeout   600;#nginx跟後端服務器連接超時時間(代理連接超時)
			proxy_send_timeout   600; #後端服務器數據回傳時間(代理髮送超時)
			proxy_read_timeout   600; #連接成功後,後端服務器響應時間(代理接收超時)
			proxy_buffer_size   8k; #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
			proxy_buffers   4 64k;#proxy_buffers緩衝區,網頁平均在32k以下的話,這樣設置
			proxy_busy_buffers_size   128k;#高負荷下緩衝大小(proxy_buffers*2)
			proxy_temp_file_write_size  128k;#設定緩存文件夾大小,大於這個值,將從upstream服務器傳
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

4、Tomcat配置

對於tomcat大家都很熟悉,只需要修改server.xml配置文件即可;

這裏我們以apache-tomcat-8.5.5爲例,分別在server目錄,解壓縮並命名爲:apache-tomcat-8.5.5-8090、apache-tomcat-8.5.5-8091

第一處端口修改:
Xml代碼 :

<!--  修改port端口:8006 倆個tomcat不能重複,端口隨意,別太小-->  
<Server port="8006" shutdown="SHUTDOWN">
第二處端口修改:
Xml代碼 :

<!-- port="8090" tomcat監聽端口,隨意設置,別太小 -->  
<Connector port="8090" protocol="HTTP/1.1"   
               connectionTimeout="20000"   
               redirectPort="8443" />

第三處端口修改:

<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


第四處session共享配置

      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->
        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="6">

          <Manager className="org.apache.catalina.ha.session.BackupManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"
                   mapSendOptions="6"/>
          <!--
          <Manager className="org.apache.catalina.ha.session.DeltaManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"/>
          -->
          <Channel className="org.apache.catalina.tribes.group.GroupChannel">
            <Membership className="org.apache.catalina.tribes.membership.McastService"
                        address="228.0.0.4"
                        port="45564"
                        frequency="500"
                        dropTime="3000"/>
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                      address="auto"
                      port="5000"
                      selectorTimeout="100"
                      maxThreads="6"/>

            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
            </Sender>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=".*\.gif|.*\.js|.*\.jpeg|.*\.jpg|.*\.png|.*\.htm|.*\.html|.*\.css|.*\.txt"/>

          <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
                    tempDir="/tmp/war-temp/"
                    deployDir="/tmp/war-deploy/"
                    watchDir="/tmp/war-listen/"
                    watchEnabled="false"/>

          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
        </Cluster>

官方文檔地址:http://tomcat.apache.org/tomcat-8.5-doc/cluster-howto.html

其次驗證tomcat,啓動兩個tomcat,不出現端口衝突即爲成功。


java項目web.xml需要配置加入

<distributable/>

驗證頁面session是否相同

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <base href="<%=basePath%>">

  <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
</head>

<body>
  SessionID:<%=session.getId()%>
  <BR>
  SessionIP:<%=request.getServerName()%>
  <BR>
  SessionPort:<%=request.getServerPort()%>
  <%
    out.println("This is Tomcat Server 11111");
  %>
</body>
</html>





參考文章地址:http://www.jianshu.com/p/47a94a3bff34


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章