Nginx+Lua+Tomcat搭建分佈式集羣

Nginx+Tomcat+cluster集羣搭建

Tomcat1 --> 帶有newrelic的主Tomcat複製版本javascript

Tomcat2 --> 純淨的相同版本的Tomcatcss

Nginx1.8html

SSL證書原始文件和密碼java

安裝Nginx

nginx1.8 download - http://nginx.org/download/nginx-1.8.0.tar.gz
	安裝nginx支持文件:
	![](http://i.imgur.com/16kENRp.png)
	--prefix 爲Nginx的安裝目錄

	![](http://i.imgur.com/HVl7fIX.png)

    下載1.0.2版本OpenSSL,並解壓
	wget http://www.openssl.org/source/openssl-1.0.2e.tar.gz

	下載Nginx_lua模塊並解壓
	wget https://github.com/chaoslawful/lua-nginx-module/archive/v0.10.4.tar.gz

	下載Lua語言
	wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz
	解壓 - make
	出現以下內容表示編譯成功
	OK        Successfully built LuaJIT
	make[1]: Leaving directory `/usr/local/src/LuaJIT-2.0.2/src'
	==== Successfully built LuaJIT 2.0.2 ====
	make install
	出現以下內容,表示安裝成功
	==== Successfully installed LuaJIT 2.0.2 to /usr/local ====
	環境變量
	export LUAJIT_LIB=/usr/local/lib
	export LUAJIT_INC=/usr/local/include/luajit-2.0
	
	安裝devel_kit
	wget https://github.com/simpl/ngx_devel_kit/archive/v0.2.19.tar.gz
	解壓

	安裝命令
	./configure --prefix=/usr/local/nginx-1.8 --with-http_stub_status_module --with-http_gzip_static_module --with-http_ssl_module --with-openssl=/usr/local/download/openssl-1.0.2e --with-http_spdy_module --add-module=/usr/local/ngx_devel_kit-0.2.19 --add-module=/usr/local/lua-nginx-module-0.10.4
	
	#--add-module=/usr/local/jakarta/nginx_jvm_route/nginx_upstream_jvm_route
	#with-http_stub_status_module  -- 監控Nginx運行狀態
	#with-http_ssl_module -- 開啓Nginx支持ssl
	#with-openssl -- 使用哪個openssl,注意這裏是openssl的源碼而不是安裝後的目錄
	#ngx_devel_kit+lua-nginx-module 是lua語言擴展包
	#SPDY 協議旨在經過壓縮、多路複用和優先級來縮短網頁的加載時間和提升安全性。(SPDY 是 Speedy 的暱音,意思是更快)

	make --嘗試安裝看看是否出錯
	make install 開始正式安裝

	若是出錯用這個命令
	ln -s /usr/local/lib/libluajit-5.1.so.2 /lib64/libluajit-5.1.so.2

配置Nginx

user  root;
	worker_processes  4;
	
	#error_log  logs/error.log;
	#error_log  logs/error.log  notice;
	#error_log  logs/error.log  info;
	
	#pid    logs/nginx.pid;
	
	events {
	    use epoll;#linux專用,速度很快
	    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;
	
		#禁止顯示nginx版本,安全性問題
	    server_tokens off;
	
	    sendfile    on;
	    #tcp_nopush   on;
	
	    #keepalive_timeout  0;
	    keepalive_timeout  120;
	
	    gzip  on;
	    gzip_min_length  1k;#1k如下文件禁用gzip
	    gzip_buffers   4 16k;
	    gzip_http_version 1.0;
	    gzip_comp_level 4;#數字大壓縮比例高,cpu負載大
	    gzip_types text/html,application/x-javascript,text/css;
	    gzip_vary on;
	
	    #improve fastcgi_buffers to solve 504error
	    fastcgi_buffers 8 128k;
	
	    #time out time
	    send_timeout 120;
	
	    #404error page
	
	    #fastcgi_intercept_errors on;
	
	  #http請求轉發 301重定向	
	  server {
	    listen     80;
	    server_name  localhost_80;
	
	    rewrite ^(.*)$  https://$host$1 permanent;
	  }
	
	  upstream tomcatserver {
	    ip_hash;#用戶所訪問的服務器綁定與ip,除非ip改變不然不會訪問其餘的server
	    server localhost:8080 weight=6;
	    server localhost:8081 weight=4 max_fails=3 fail_timeout=30s; #backup 備用服務器
		#1.輪詢(默認)
		#2.fair; 響應優先/upstream_fair支持
		#3.url_hash 相同的url分到相同後端 - 靜態緩存
		#4.ip_hash ip綁定,相同ip分到相同後端 - 弊端
		#jvm_route第三方。目前支持版本1.4,sessionId綁定
	  }
	  
	  #2 - 請求頻率 
	  #令牌原理,cooke的token做爲標識符,每秒限制x個請求
	  limit_req_zone $cookie_token zone=session_limit:10m rate=30r/s;

	  # HTTPS server
	  server {
	    listen    443 ssl spdy;
	    server_name  dev.seoclarity.net;
	
	    ssl on;
	    ssl_certificate /home/ssl/wildcard/chained.crt;
	    ssl_certificate_key /home/ssl/wildcard/seoclarity_net.key;
		#openssl支持的加密版本,拒絕sslv2 和 sslv3
	    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
	    #ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;
		##只支持安全的加密算法,拒絕例如MD5之類的非安全算法
	    ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5;
	    ssl_prefer_server_ciphers on;
		#ssl加密過的key緩存時間10分鐘,不須要每次都和客戶端握手
	    ssl_session_cache shared:SSL:10m;
		#徹底正向加密(Perfect Forward Secrecy,PFS)
		#http://baike.baidu.com/link?url=HzOVQe-j2wN4JDJVFx_EiuPBoZp0TGN2sn8R_n4We2VedkkRX1B8UlMCO6qzIzEfXKzgGn0x_9PK7o5bAOJQha
		#黑客保存攔截的數據待破解後一次性解密,PFS應對
		#加密的隨機數默認1024字節
	    ssl_dhparam /home/ssl/wildcard/dhparam.pem;
	    ssl_session_timeout 30m;
		#緩衝區
		ssl_buffer_size 1400;

	    index  index.html index.htm index.jsp;

	    location / {
	        proxy_pass http://tomcatserver;
			
			#2 - 請求頻率
			#令牌原理,cooke的token做爲標識符
			#burst做爲備用的訪問請求數,好比上面限制30r/s可是第一秒訪問30+burst的請求也是容許的,可是第二秒將嚴格限制30r/s
			#nodelay,若是不設置該選項,嚴格使用平均速率限制請求數
			#第1秒25個請求時,5個請求放到第2秒執行
			#設置了的話,25個請求嚴格在第一秒,超過的請求直接503
			limit_req zone=session_limit burst=10;#nodelay

			#1 - 限制請求
			#API、爬蟲 禁用 - CC攻擊
			rewrite_by_lua '
				#從cookie中取隨機數
			    local random = ngx.var.cookie_random
				#cookie中無隨機數
			    if(random == nil) then
					#生成隨機數
			        random = math.random(999999)
			    end
				#ip+隨機數 MD5加密 --> token
			    local token = ngx.md5("opencdn" .. ngx.var.remote_addr .. random)
				#若是cookie中token != 計算的token
				if (ngx.var.cookie_token ~= token) then
					#放置token
			        ngx.header["Set-Cookie"] = {"token=" .. token, "random=" .. random}
			        #讓客戶端從新請求
					return ngx.redirect(ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.uri)
			    end
			';

	        proxy_redirect off;
			#後端經常使用參數轉發,不加這些後端常常取到客戶ip是127.0.0.1
	        proxy_set_header Host $host;
	        proxy_set_header X-Real-IP $remote_addr;
	        proxy_set_header REMOTE-HOST $remote_addr;
	        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	        proxy_set_header Cookie $http_cookie;
			#文件上傳最大size
	        client_max_body_size 5m;
	        client_body_buffer_size 256k;
	        proxy_connect_timeout 10;
	        proxy_send_timeout 30;
	        proxy_read_timeout 120;
	        proxy_buffer_size 256k;
	        proxy_buffers 4 256k;
	        proxy_busy_buffers_size 256k;
	        proxy_temp_file_write_size 256k;
	        #proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
	    }
	
		#監控nginx狀態
	    location /ngx_status {
	        stub_status on;
	        access_log off;
	        #allow 127.0.0.1;
	        #deny all;
	    }
	
		#靜態文件訪問
	    location ~* ^.+\.(swf|gif|png|jpg|js|css)$ {
	        root /home/actonia/source/0729/trunk/saas/WebContent;
	        expires 15m;
	    }
	
	    #error page
	    error_page   500 502 503 504  /50x.html;
	    location = /50x.html {
	        root   html;
	    }
	  }
	}

Tomcat1配置文件

<?xml version='1.0' encoding='utf-8'?>

<Server port="8035" shutdown="SHUTDOWN">

  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JasperListener" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <GlobalNamingResources>

    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">

    <Connector port="8080" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true"
               compression="on"
               maxPostSize="0"
               URIEncoding="UTF-8"
               compressionMinSize="2048"
               noCompressionUserAgents="gozilla, traviata"
               compressableMimeType="text/html,text/xml,text/javascript,text/css,application/json" />

    <Connector port="8039" protocol="AJP/1.3" redirectPort="443" URIEncoding="UTF-8" />

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1nginx">

      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="8">

          <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="33451"#這個端口號2個要同樣(相同廣播地址相同端口認定爲同一個組播)
                        frequency="500"
                        dropTime="3000"/>
                        <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                                address="auto"#組播
                                port="4000"
                                autoBind="100" #從4000開始,100之內隨機挑選一個
                                selectorTimeout="5000"
                                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.MessageDispatch15Interceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=""/>
          <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

          <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.JvmRouteSessionIDBinderListener"/>
          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>

        </Cluster>

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt" pattern="combined" resolveHosts="false"/>

      </Host>
    </Engine>
  </Service>
</Server>

Tomcat2配置文件

<?xml version='1.0' encoding='utf-8'?>
<Server port="8036" shutdown="SHUTDOWN">

  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JasperListener" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <GlobalNamingResources>

    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <Service name="Catalina">

    <Connector port="8081" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true"
               compression="on"
               maxPostSize="0"
               URIEncoding="UTF-8"
               compressionMinSize="2048"
               noCompressionUserAgents="gozilla, traviata"
               compressableMimeType="text/html,text/xml,text/javascript,text/css,application/json" />

    <Connector port="8040" protocol="AJP/1.3" redirectPort="443" URIEncoding="UTF-8" />

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2nginx">

      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="8">

          <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="33451"#
                        frequency="500"
                        dropTime="3000"/>
                <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                                address="auto"#
                                port="4000"#
                                autoBind="100"
                                selectorTimeout="5000"
                                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.MessageDispatch15Interceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
                 filter=""/>
          <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

          <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.JvmRouteSessionIDBinderListener"/>
          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>

        </Cluster>

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt" pattern="combined" resolveHosts="false"/>

      </Host>
    </Engine>
  </Service>
</Server>

如下是摘抄的組播解釋

<!-- 
    Cluster(集羣,族) 節點,若是你要配置tomcat集羣,則須要使用此節點.
    className 表示tomcat集羣時,之間相互傳遞信息使用那個類來實現信息之間的傳遞.
    channelSendOptions能夠設置爲二、四、八、10,每一個數字表明一種方式
    2 = Channel.SEND_OPTIONS_USE_ACK(確認發送)
    4 = Channel.SEND_OPTIONS_SYNCHRONIZED_ACK(同步發送) 
    8 = Channel.SEND_OPTIONS_ASYNCHRONOUS(異步發送)
    在異步模式下,能夠經過加上確認發送(Acknowledge)來提升可靠性,此時channelSendOptions設爲10
-->
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">
    <!--
        Manager決定如何管理集羣的Session信息。Tomcat提供了兩種Manager:BackupManager和DeltaManager
        BackupManager-集羣下的全部Session,將放到一個備份節點。集羣下的全部節點均可以訪問此備份節點
        DeltaManager-集羣下某一節點生成、改動的Session,將複製到其餘節點。
        DeltaManager是Tomcat默認的集羣Manager,能知足通常的開發需求
        使用DeltaManager,每一個節點部署的應用要同樣;使用BackupManager,每一個節點部署的應用能夠不同.

        className-指定實現org.apache.catalina.ha.ClusterManager接口的類,信息之間的管理.
        expireSessionsOnShutdown-設置爲true時,一個節點關閉,將致使集羣下的全部Session失效
        notifyListenersOnReplication-集羣下節點間的Session複製、刪除操做,是否通知session listeners
        maxInactiveInterval-集羣下Session的有效時間(單位:s)。
        maxInactiveInterval內未活動的Session,將被Tomcat回收。默認值爲1800(30min)
    -->
    <Manager className="org.apache.catalina.ha.session.DeltaManager"
             expireSessionsOnShutdown="false"
             notifyListenersOnReplication="true"/>

    <!--
        Channel是Tomcat節點之間進行通信的工具。
        Channel包括5個組件:Membership、Receiver、Sender、Transport、Interceptor
    -->
    <Channel className="org.apache.catalina.tribes.group.GroupChannel">
         <!--
            Membership維護集羣的可用節點列表。它能夠檢查到新增的節點,也能夠檢查到沒有心跳的節點
            className-指定Membership使用的類
            address-組播地址
            port-組播端口
            frequency-發送心跳(向組播地址發送UDP數據包)的時間間隔(單位:ms)。默認值爲500
            dropTime-Membership在dropTime(單位:ms)內未收到某一節點的心跳,則將該節點從可用節點列表刪除。默認值爲3000

            注: 組播(Multicast):一個發送者和多個接收者之間實現一對多的網絡鏈接。
                一個發送者同時給多個接收者傳輸相同的數據,只需複製一份相同的數據包。
                它提升了數據傳送效率,減小了骨幹網絡出現擁塞的可能性
                相同組播地址、端口的Tomcat節點,能夠組成集羣下的子集羣
         -->
        <Membership className="org.apache.catalina.tribes.membership.McastService"
                    address="228.0.0.4"
                    port="45564"
                    frequency="500"
                    dropTime="3000"/>

        <!--
            Receiver : 接收器,負責接收消息
            接收器分爲兩種:BioReceiver(阻塞式)、NioReceiver(非阻塞式)

            className-指定Receiver使用的類
            address-接收消息的地址
            port-接收消息的端口
            autoBind-端口的變化區間
            若是port爲4000,autoBind爲100,接收器將在4000-4099間取一個端口,進行監聽
            selectorTimeout-NioReceiver內輪詢的超時時間
            maxThreads-線程池的最大線程數
        -->
        <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                  address="auto"
                  port="4000"
                  autoBind="100"
                  selectorTimeout="5000"
                  maxThreads="6"/>

        <!--
            Sender : 發送器,負責發送消息
            Sender內嵌了Transport組件,Transport真正負責發送消息
        -->
        <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
            <!--
                Transport分爲兩種:bio.PooledMultiSender(阻塞式)、nio.PooledParallelSender(非阻塞式) 
            -->
            <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
        </Sender>

        <!--
            Interceptor : Cluster的攔截器
            TcpFailureDetector-網絡、系統比較繁忙時,Membership可能沒法及時更新可用節點列表,
            此時TcpFailureDetector能夠攔截到某個節點關閉的信息,
            並嘗試經過TCP鏈接到此節點,以確保此節點真正關閉,從而更新集羣能夠用節點列表                 
        -->
        <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>

        <!--
            MessageDispatch15Interceptor-查看Cluster組件發送消息的方式是否設置爲
            Channel.SEND_OPTIONS_ASYNCHRONOUS(Cluster標籤下的channelSendOptions爲8時)。
            設置爲Channel.SEND_OPTIONS_ASYNCHRONOUS時,
            MessageDispatch15Interceptor先將等待發送的消息進行排隊,而後將排好隊的消息轉給Sender
        -->
        <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
    </Channel>

    <!--
        Valve : 能夠理解爲Tomcat的攔截器
        ReplicationValve-在處理請求先後打日誌;過濾不涉及Session變化的請求                   
        vmRouteBinderValve-Apache的mod_jk發生錯誤時,保證同一客戶端的請求發送到集羣的同一個節點
    -->
    <Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=""/>
    <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

    <!--
        Deployer : 同步集羣下全部節點的一致性。Deployer沒試驗成功過。。。
     -->
     <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
                   tempDir="/tmp/war-temp/"
                   deployDir="/tmp/war-deploy/"
                   watchDir="/tmp/war-listen/"
                   watchEnabled="false"/>
    <!--
        ClusterListener : 監聽器,監聽Cluster組件接收的消息
        使用DeltaManager時,Cluster接收的信息經過ClusterSessionListener傳遞給DeltaManager
    -->
    <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>

Nginx證書提取方法

http://blog.sina.com.cn/s/blog_4b81125f0100ky4e.htmlnode

服務器須要啓用組播

查看是否啓用組播linux

netstat -gnnginx

由於tomcat的session同步功能須要用到組播,默認都是打開的.
能夠經過指令打開
route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0

其餘注意事項

項目修改:

1.applicationContext-security.xml 取消https
2.web.xml 啓用分佈式: <distributable/> 不然會出現session無端丟失狀況

關於Tomcat/部署代碼 一些其餘改動

1.Tomcat配置
1.結束熱啓動
  Tomcat conf/Catalina/localhost/ROOT.xml
  刪除reloadable屬性,編譯時不會影響Tomcat正常運行
  
2.Tomcat8 cluster官方配置
  <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
             channelSendOptions="8">

      <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="4000"
                  autoBind="100"
                  selectorTimeout="5000"
                  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.MessageDispatch15Interceptor"/>
      </Channel>

      <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
             filter=""/>
      <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

      <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>

3.Tomcat自帶session持久化
取消註釋,關閉功能。須要實現序列化
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
2.關於newrelic配置
若是Tomcat路徑變化,須要修改bin/下的catalina.sh 中 NR_JAR 這個變量
通用設置 : 
# ---- New Relic switch automatically added to start command on 2015 Oct 08, 05:12:50
NR_JAR="$CATALINA_BASE"/newrelic/newrelic.jar; export NR_JAR
JAVA_OPTS="$JAVA_OPTS -javaagent:$NR_JAR"; export JAVA_OPTS
3.整合Tomcat輸出日誌
1.進入 "從" Tomcat

2.vim bin/catalina.sh

3.增長變量
  #---- Main Tomcat Path for log----
  CATALINA_MAIN_BASE="主Tomcat Path"

4.在全部的 
  -Dcatalina.base=
  下增長 
  -Dcatalina.mainbase="$CATALINA_MAIN_BASE" \

5.找到 CATALINA_OUT="$CATALINA_BASE"/logs/catalina.out  
  修改成 CATALINA_OUT="$CATALINA_MAIN_BASE"/logs/catalina.out  

6.打開conf/logging.properties文件
  替換全部${catalina.base}爲${catalina.mainbase}

7.重啓"從"Tomcat,進入主Tomcat查看Log
4.Nginx配置
1.nginx默認的fastcgi進程響應緩衝區過小致使504 Gateway Time-out」錯誤。
  fastcgi_buffers 8 128k;

2.提高超時等待時間,不要太長吃內存
  keepalive_timeout  120;

3.解決Cookie問題
  location中
  proxy_set_header Cookie $http_cookie;
  
4.限制訪問頻率
  limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
相關文章
相關標籤/搜索