nginx整合tomcat集群並做session共用----測試案例

来源:http://www.cnblogs.com/jstarseven/archive/2016/01/17/5137838.html
-Advertisement-
Play Games

最近出於好奇心,研究了一下tomcat集群配置,並整合nginx,實現負載均衡,session共用,寫篇記錄,防止遺忘。---------菜雞的自我修煉。說明:博主採用一個web項目同時部署到兩台tomcat下,(tomcat-A,tomca-B),使用nginx做反向代理,按照設置的權值,將請求分...


最近出於好奇心,研究了一下tomcat集群配置,並整合nginx,實現負載均衡,session共用,寫篇記錄,防止遺忘。---------菜雞的自我修煉。

 

說明:博主採用一個web項目同時部署到兩台tomcat下,(tomcat-A,tomca-B),使用nginx做反向代理,按照設置的權值,將請求分發到後臺的tomcatA/tomcatB,並且實現session共用。

    

配置好本地功能變數名稱指向:修改host文件:添加 127.0.0.1  www.domain.com.cn

新建項目:tiny-demo-operation 採用springmvc 配置好springmvc.xml配置文件

建立SessionShareSetController和SessionShareGetController

目錄如下:

SessionShareSetController代碼:

 1 package com.tiny.session.share.controller;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 import javax.servlet.http.HttpSession;
 6 
 7 import org.springframework.stereotype.Controller;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 
10 @Controller
11 @RequestMapping("/sessionShare")
12 public class SessionShareSetController {
13 
14     @RequestMapping("/sessionSet")
15     public String sessionSet(HttpServletRequest request,
16             HttpServletResponse response) throws Exception {
17 
18         HttpSession session = request.getSession();
19         String name = "tinyseven-demo-operation"+"---";
20         String remote = request.getRemoteHost() + "---"
21                 + request.getRemoteAddr() + "---" + request.getRemotePort()
22                 + "---";
23         String local = request.getLocalName() + "---" + request.getLocalAddr()
24                 + "---" + request.getLocalPort() + "---";
25         String server = request.getServerName() + "---"
26                 + request.getServerPort() + "---";
27         request.setAttribute("name", name);
28         request.setAttribute("remote", remote);
29         request.setAttribute("local", local);
30         request.setAttribute("server", server);
31 
32         session.setAttribute("name", name);
33         return "sessionshare/sessionSet";
34     }
35 
36 }
View Code

SessionShareGetController代碼:

 1 package com.tiny.session.share.controller;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 
 8 @Controller
 9 @RequestMapping("/sessionShare")
10 public class SessionShareGetController {
11 
12     @RequestMapping("/sessionGet")
13     public String sessionGet(HttpServletRequest request) throws Exception {
14 
15         String name = (String) request.getSession().getAttribute("name")
16                 + "---";
17         String remote = request.getRemoteHost() + "---"
18                 + request.getRemoteAddr() + "---" + request.getRemotePort()
19                 + "---";
20         String local = request.getLocalName() + "---" + request.getLocalAddr()
21                 + "---" + request.getLocalPort() + "---";
22         String server = request.getServerName() + "---"
23                 + request.getServerPort() + "---";
24         request.setAttribute("name", name);
25         request.setAttribute("remote", remote);
26         request.setAttribute("local", local);
27         request.setAttribute("server", server);
28         return "sessionshare/sessionGet";
29 
30     }
31 }
View Code

新建jsp頁面:

目錄如下:

sessionSet.jsp部分代碼:

<body>
    當前用戶設置session--server-->>${server}</br>
    當前用戶設置session--remote-->>${remote}</br>
    當前用戶設置session--local-->>${local}</br>
    當前用戶設置session--name-->>${name}</br>
</body>
View Code

sessionGet.jsp部分代碼:

1 <body>
2     當前用戶請求的server-->>${server}</br>
3     當前用戶請求的remote-->>${remote}</br>
4     當前用戶請求的local-->>${local}</br>
5     當前用戶請求的name-->>${name}</br>
6 </body>
View Code

 

 

一、準備兩台tomcat,建立起tomcat集群。

博主使用 apache-tomcat-6.0.37

路徑分別為:E:\Server\apache-tomcat-6.0.37-node-A

                 E:\Server\apache-tomcat-6.0.37-node-B

分別修改A/B的server.xml保證兩台tomcat可以正常啟動,避免埠衝突,並且建立起兩台tomcat的集群。

1.修改A的server.xml,在所有port前面加1,例如(<Server port="8005" shutdown="SHUTDOWN">修改成<Server port="18005" shutdown="SHUTDOWN">其他類似

修改<Engine name="Catalina" defaultHost="localhost" >為<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">

 

2.修改B的server.xml,在所有port前面加2,例如(<Server port="8005" shutdown="SHUTDOWN">修改成<Server port="28005" shutdown="SHUTDOWN">其他類似

修改<Engine name="Catalina" defaultHost="localhost" >為<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2">

此時兩台tomcat應該都可以成功啟動了。

 

3.建立起兩台tomcat的集群服務。

分別取消掉A/B server.xml文件中

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

 的註釋。

重新啟動A、B tomcat(運行bin中的startup.bat)發現這次啟動比上次多了以下信息,表示兩個tomcat節點已經建立起了關聯。

二、發佈項目到tomcatA、tomcatB下,並且配置session共用。

1.修改tomcaA、tomcatB的server.xml文件。

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

<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->

<!-- Access log processes all example.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
-->
<Context docBase="E:\javaWorkspace\tiny-demo-operation\WebRoot" reloadable="true" path="/tiny-demo-operation" crossContext="true" source="org.eclipse.jst.jee.server:tiny-demo-operation"/> 此處為添加內容

</Host>

2、修改所發佈項目的web.xml文件

在web.xml文件的</web-app>之前添加

<!-- session共用配置 -->
<distributable />

 

此時當前項目在兩台tomcat可以做到session共用了,效果如下:

訪問tomcatA下的項目,設置session:

訪問tomcatB下的項目,獲取session:

三、整合nginx,實現請求分發。此處使用的是nginx1.5.0版本

1.修改nginx.conf  修改後

 1 #Nginx所用用戶和組,window下不指定
 2 #user  niumd niumd;
 3 #工作的子進程數量(通常等於CPU數量或者2倍於CPU)
 4 
 5 worker_processes  2;
 6 
 7 #錯誤日誌存放路徑
 8 #error_log  logs/error.log;
 9 #error_log  logs/error.log  notice;
10 
11 error_log  logs/error.log  info;
12 
13 #指定pid存放文件
14 
15 pid        logs/nginx.pid;
16 
17 events {
18     #使用網路IO模型linux建議epoll,FreeBSD建議採用kqueue,window下不指定。
19     #use epoll;
20     #允許最大連接數
21     worker_connections  2048;
22 }
23 
24 http {
25 
26     include       mime.types;
27     default_type  application/octet-stream;
28     #定義日誌格式
29     #log_format  main  '$remote_addr - $remote_user [$time_local] $request '
30     #                  '"$status" $body_bytes_sent "$http_referer" '
31     #                  '"$http_user_agent" "$http_x_forwarded_for"';
32     #access_log  off;
33     access_log  logs/access.log;
34     client_header_timeout  3m;
35     client_body_timeout    3m;
36     send_timeout           3m;
37     client_header_buffer_size    1k;
38     large_client_header_buffers  4 4k;
39     sendfile        on;
40     tcp_nopush      on;
41     tcp_nodelay     on;
42     #keepalive_timeout  75 20;
43     include    gzip.conf;
44     include       proxy.conf;
45 
46     upstream localhost {
47             #根據ip計算將請求分配各那個後端tomcat,許多人誤認為可以解決session問題,其實並不能。
48             #同一機器在多網情況下,路由切換,ip可能不同
49             #ip_hash;
50             #weigth參數表示權值,權值越高被分配到的幾率越大
51             server localhost:18080 weight=5;
52             server localhost:28080 weight=5;
53 
54     }
55     
56     server {
57     
58     listen       80;
59     server_name  localhost;
60 
61         location / { 
62             root E:/javaWorkspace/tiny-demo-operation/WebRoot;
63             index index.html index.htm;
64             
65         }
66         
67         location ~ \.(html|js|css|png|gif)$ {  
68             root E:/javaWorkspace/tiny-demo-operation/WebRoot;
69         } 
70 
71         location ~ \.(jsp|action)$ {
72             proxy_connect_timeout   3;
73             proxy_send_timeout      30;
74             proxy_read_timeout      30;
75             proxy_pass http://localhost;
76         }
77     }
78 }
View Code

2.重新啟動nginx

訪問虛擬主機下的當前項目,nginx自動實現請求分發,效果如下:

分發到tomcatB下的tiny-demo-operation,設置session中的屬性值name。

 

分發tomcatA下的tiny-demo-operation,獲取session中的屬性值name。

 

 

至此,簡單實現了nginx整合tomcat集群,實現負載均衡,session共用的測試案例。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.首先來幾個英文縮寫的含義 javaSE 標準版javaEE 企業版 javaME 微型版 sdk:soft developement kit,開發工具包,包含jdk jdk:java developement kit jre:java runtime environment jvm...
  • 是的,這篇blogs是一個總結篇,最開始的時候我提到過,對於java容器或集合的學習也可以看做是對數據結構的學習與應用。在前面我們分析了很多的java容器,也接觸了好多種常用的數據結構,今天我們就來總結下這些內容。 下麵我們以數據結構的維度來總結下,在Java集合的實現過程中,底層到底使用了哪...
  • 今天,Alice 和 Bob 兩個人發明瞭一個新的取石子游戲。我們將 n 枚石子擺放成一行,從左到右每枚石子有兩個參數,能量ei和得分ai。Alice 和 Bob 兩人輪流決策,從左到右依次取石子,Alice 先手。每個回合,玩家可以選擇下列兩個操作之一:1. 消耗一個單位的能量,跳過這個回合。2....
  • 「C語言」原碼反碼補碼與位運算
  • 學過C語言的小猿們都知道,C語言中有很多的運算符:賦值運算符、算術運算符、邏輯運算符、關係運算符、條件運算符、逗號運算符、位運算符…… 運算符在代碼中發揮著極其重要的作用,Swift中也有很多的運算符,大部分與C中的運算符相似甚至相同,但也有一些改動和補充,接下來就簡單介紹一下這些與 'C...
  • int WINAPI WinMain(HINSTANCE HInstance,HINSTANCE HPreInstance,LPSTR szCmdLine,intCmdShown){MassageBox(NULL,TEXT("你好"),TEXT("window程式"),MB_OK);}hInstan...
  • 先上利於理解的代碼: 1 #coding:utf-8 2 def consumer(): 3 c_r = '' 4 while 1: 5 m = yield c_r 6 if not m: 7 return 8 ...
  • 自動載入(phalcon\Loader)轉載請註明來源一、php文件引入 通過 include() 或 require() 函數,可以在PHP程式執行之前在該文件中插入一個文件的內容。區別:處理錯誤的方式不同。include() 函數會生成一個警告(但是腳本會繼續執行),而 require() 函....
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...