使用Nginx做爲Tomcat的負載平衡器,Tomcat的會話Session數據存儲在Redis,可以實現0當機的7x24運營效果。由於將會話存儲在Redis中,所以Nginx就沒必要配置成stick粘粘某個Tomcat方式,這樣才能真正實現後臺多個Tomcat負載平衡,用戶請求可以發往任何一個tomcat主機,當咱們須要部署新應用代碼時,只要中止任何一臺tomcat,全部當前在線用戶都會導向到運行中的tomcat實例,由於會話數據被序列化到Redis,在線用戶不會受到影響,一旦停掉的tomcat實例上線,另外其餘重複部署過程。php
工具 | 版本 | 端口 |
nginx | 1.9.4 | 127.0.0.1:80(默認) |
tomcat7_1 | 7.0.61 | 127.0.0.1:8091 |
tomcat7_2 | 7.0.61 | 127.0.0.1:8092 |
tomcat7_3 | 7.0.61 | 127.0.0.1:8093 |
redis |
2.7.3+ |
127.0.0.1:6379(默認) |
介紹:tomcat-redis-session-manager 是一個用來將 Tomcat 的 Session 數據存儲在 Redis 庫中的項目。html
官網:https://github.com/jcoleman/tomcat-redis-session-managerjava
從官網下載相關源代碼,找到build.gradle文件,因爲做者使用了第三方倉庫(sonatype),須要註冊賬號,太麻煩,註釋後直接使用maven中央倉庫,同時註釋簽名相關腳本並增長依賴包的輸出腳本 copyJars(dist目錄),修改後的 build.gradle 文件以下:nginx
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.61' compile group: 'redis.clients', name: 'jedis', version: '2.7.3' 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.61' } 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' } } } } } }
我對版本進行了修改,tomcat使用7.0.61版本,redis使用2.7.3版本。git
執行gradle命令構建源碼,編譯輸出tomcat-redis-session-manager-master 及依賴jar包github
gradle build -x test copyJars
生成的jar以下:
web
安裝配置兩臺 tomcat web服務器,分別修改 Connector 端口號爲8091和8092,並確保都能正常工做,固然若是分佈在不一樣的主機則可使用相同端口號。redis
tomcat1:Server port="8005",Connector port="8091",ajp Connector port="8009"apache
tomcat2:Server port="8006",Connector port="8092",ajp Connector port="8010"windows
tomcat3:Server port="8007",Connector port="8093",ajp Connector port="8011"
新建web項目test,新建index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Nginx+tomcat負載均衡+redis會話管理</title> </head> <body> <h1><font color="blue">集羣節點1</font></h1> <table align="centre" border="1"> <tr> <td>Session ID</td> <td><%= session.getId() %></td> </tr> <tr> <td>Created on</td> <td><%= session.getCreationTime() %></td> </tr> </table> <p> </body> </html>
分別部署運行:
看到實驗結果是,兩個web顯示的是不一樣的內容,不一樣的session。
爲了實現session共享,咱們要進行下一步操做,就是使用上面編譯的tomcat-redis-session-manager,做爲tomcat session得管理器。
一、分別將第二步生成的 tomcat-redis-session-manager-master 及依賴jar包覆蓋到 tomcat 安裝目錄的 lib 文件夾
二、分別修改3臺 tomcat 的 context.xml 文件,使 tomcat-redis-session-manager-master 做爲session管理器,同時指定redis地址和端口。
context.xml 增長如下配置:
<Context> <!-- Default set of monitored resources --> <WatchedResource>WEB-INF/web.xml</WatchedResource> <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" host="localhost" port="6379" database="0" maxInactiveInterval="60" /> </Context>
三、重啓tomcat
#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 site { server localhost:8091; server localhost:8092; server localhost:8093; } 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 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 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; # } #} }
重啓nginx
nginx -s reload
訪問web項目,出現下面錯誤:
這是由於redis服務器尚未啓動致使。我是在windows10 64位下測試,因此咱們須要下載相關版本,
官方的下載地址是: http://redis.io/download
在win64一欄中能夠看到redis本來是沒有windows版本的,windows版本是 Microsoft Open Tech團隊開的
https://github.com/MSOpenTech/redis
解壓便可開箱使用
使用命令【redis-server.exe redis.windows.conf】,啓動redis 服務【若是您沒出現以下的錯誤,直接跳過】。若是您也像我同樣出現以下的錯誤,不用急,總有解決辦法滴!
解決辦法:
根據提示,是 maxheap 標識有問題,打開配置文件 redis.windows.conf ,搜索 maxheap , 而後直接指定好內容便可.
......
#
# maxheap <bytes>
maxheap 1024000000
.......
而後再次啓動,OK,成功.
接着刷新tomcat服務器頁面
你會發現成功了,三個服務器的session值徹底同樣,不管如何刷新都不會發生改變了
接着咱們使用nginx代理服務器進行訪問web,你會發現驚喜
咱們反覆刷新頁面,頁面會在不一樣的頁面進行顯示,可是session保持了一致性。這是由於咱們使用了nginx反向代理,當咱們的請求到達nginx得時候反向代理倒指定服務器,nginx配置了默認輪詢負載方式,因此就完成上述的現狀。
如今咱們使用 redis-cli 鏈接 redis 服務器去查看下如何。
至此實現了基於nginx負載均衡下 tomcat 集羣的 session 一致性。