基于nginx tomcat redis分布式web應用的session共享配置
一、前言
nginx 作為目前最流行的開源反向代理HTTP Server,用于實現資源緩存、web server負載均衡等功能,由于其輕量級、高性能、高可靠等特點在互聯網項目中有著非常普遍的應用,相關概念網上有豐富的介紹。分布式web server集群部署后需要實現session共享,針對 tomcat 服務器的實現方案多種多樣,比如 tomcat cluster session 廣播、nginx IP hash策略、nginx sticky module等方案,本文主要介紹了使用 redis 服務器進行 session 統一存儲管理的共享方案。
相關應用結構參照下圖:
二、環境配置
測試環境基于 Linux CentOS 6.5,請先安裝 tomcat、redis、nginx 相關環境,不作詳細描述,本文測試配置如下:
Version IP_Port
nginx 1.6.2 10.129.221.70:80
tomcat_1 7.0.54 10.129.221.70:8080
tomcat_2 7.0.54 10.129.221.70:9090
redis 2.8.19 10.129.221.70:6379
三、構建 tomcat-redis-session-manager-master
1、由于源碼構建基于 gradle,請先配置 gradle 環境。
2、從 github 獲取 tomcat-redis-session-manager-master 源碼,地址如下:
https://github.com/jcoleman/tomcat-redis-session-manager
3、找到源碼中的 build.gradle 文件,由于作者使用了第三方倉庫(sonatype),需要注冊帳號,太麻煩,注釋后直接使用maven中央倉庫,同時注釋簽名相關腳本并增加依賴包的輸出腳本 copyJars(dist目錄),修改后的 build.gradle 文件如下:
apply plugin: 'java' apply plugin: 'maven' apply plugin: 'signing' group = 'com.orangefunction' version = '2.0.0' repositories { mavenCentral() } compileJava { sourceCompatibility = 1.7 targetCompatibility = 1.7} dependencies { compile group: 'org.apache.tomcat', name: 'tomcat-catalina', version: '7.0.27' compile group: 'redis.clients', name: 'jedis', version: '2.5.2' compile group: 'org.apache.commons', name: 'commons-pool2', version: '2.2' //compile group: 'commons-codec', name: 'commons-codec', version: '1.9' testCompile group: 'junit', name: 'junit', version: '4.+' testCompile 'org.hamcrest:hamcrest-core:1.3' testCompile 'org.hamcrest:hamcrest-library:1.3' testCompile 'org.mockito:mockito-all:1.9.5' testCompile group: 'org.apache.tomcat', name: 'tomcat-coyote', version: '7.0.27' } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from 'build/docs/javadoc' } task sourcesJar(type: Jar) { from sourceSets.main.allSource classifier = 'sources' } artifacts { archives jar archives javadocJar archives sourcesJar }//signing {// sign configurations.archives//} task copyJars(type: Copy) { from configurations.runtime into 'dist' } uploadArchives { repositories { mavenDeployer { beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } //repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { // authentication(userName: sonatypeUsername, password: sonatypePassword) //} //repository(url: "https://oss.sonatype.org/content/repositories/snapshots") { // authentication(userName: sonatypeUsername, password: sonatypePassword) //} pom.project { name 'tomcat-redis-session-manager' packaging 'jar' description 'Tomcat Redis Session Manager is a Tomcat extension to store sessions in Redis' url 'https://github.com/jcoleman/tomcat-redis-session-manager' issueManagement { url 'https://github.com:jcoleman/tomcat-redis-session-manager/issues' system 'GitHub Issues' } scm { url 'https://github.com:jcoleman/tomcat-redis-session-manager' connection 'scm:git:git://github.com/jcoleman/tomcat-redis-session-manager.git' developerConnection 'scm:git:git@github.com:jcoleman/tomcat-redis-session-manager.git' } licenses { license { name 'MIT' url 'http://opensource.org/licenses/MIT' distribution 'repo' } } developers { developer { id 'jcoleman' name 'James Coleman' email 'jtc331@gmail.com' url 'https://github.com/jcoleman' } } } } } }
4、執行gradle命令構建源碼,編譯輸出tomcat-redis-session-manager-master 及依賴jar包
gradle build -x test copyJars
所有輸出列表文件如下:
四、tomcat 配置
安裝配置兩臺 tomcat web服務器,分別修改 Connector 端口號為8080和9090,并確保都能正常工作,當然如果分布在不同的主機則可以使用相同端口號。
五、編寫測試頁面
為了區別2臺tomcat的訪問,分別編寫頁面并打包部署:
1、為tomcat_1編寫測試頁面,顯示 “ response from tomcat_1 ”,同時頁面提供按鈕顯示當前session值,打包并發布到 tomcat_1 服務器;
2、為tomcat_2編寫測試頁面,顯示 “ response from tomcat_2 ”,同時頁面提供按鈕顯示當前session值,打包并發布到 tomcat_2 服務器;
此時分別訪問 http://10.129.221.70:8080 和 http://10.129.221.70:9090 地址,因為訪問的是不同web服務器,所以各自顯示不同的頁面內容及session值肯定不同。
六、tomcat session manager 配置
修改配置使用 tomcat-redis-session-manager-master 作為 tomcat session 管理器
1、分別將第三步生成的 tomcat-redis-session-manager-master 及依賴jar包覆蓋到 tomcat 安裝目錄的 lib 文件夾
2、分別修改2臺 tomcat 的 context.xml 文件,使 tomcat-redis-session-manager-master 作為session管理器,同時指定redis地址和端口。
context.xml 增加以下配置:
<Context> <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" host="localhost" port="6379" database="0" maxInactiveInterval="60" /></Context>
3、分別重啟2臺 tomcat 服務器。
七、nginx 配置
1、修改 default.conf 配置文件,啟用 upstream 負載均衡 tomcat Cluster,默認使用輪詢方式。
upstream site { server localhost:8080; server localhost:9090; } server { listen 80; server_name localhost; #charset koi8-r; #access_log /var/log/nginx/log/host.access.log main; location / { #root /usr/share/nginx/html; #index index.html index.htm; index index_tel.jsp index.jsp index.html index.htm ; 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_buffers 32 4k; proxy_connect_timeout 3; proxy_send_timeout 30; proxy_read_timeout 30; proxy_pass http://site; } #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 /usr/share/nginx/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; #}}
2、nginx 重新加載配置
nginx -s reload
八、測試結果
1、訪問 http://10.129.221.70:8080 直接請求到tomcat_1服務器,
顯示 “ response from tomcat_1 ”, session 值為 ‘56E2FAE376A47F1C0961D722326B8423’;
2、訪問 http://10.129.221.70:9090 直接請求到tomcat_2服務器,
顯示 “ response from tomcat_2 ”, session 值為 ‘56E2FAE376A47F1C0961D722326B8423’;
3、訪問 http://10.129.221.70 (默認80端口)請求到 nginx 反向代理到指定Web服務器,由于默認使用輪詢負載方式,
反復刷新頁面顯示的內容在“ response from tomcat_1 ” 和 “ response from tomcat_2 ”之間切換,但 session 值保持為 ‘56E2FAE376A47F1C0961D722326B8423’;
4、使用 redis-cli 連接 redis 服務器,查看會顯示有 “56E2FAE376A47F1C0961D722326B8423” key的 session 數據,value為序列化數據。
九、至此實現了基于nginx負載均衡下 tomcat 集群的 session 一致性。
jar包下載地址:http://pan.baidu.com/s/1geq7amR