1. 程式人生 > >基於nginx tomcat-redis-session-manager實現session共享

基於nginx tomcat-redis-session-manager實現session共享

一、前言

nginx 作為目前最流行的開源反向代理HTTP Server,用於實現資源快取、web
server負載均衡等功能,由於其輕量級、高效能、高可靠等特點在網際網路專案中有著非常普遍的應用,相關概念網上有豐富的介紹。分散式web
server叢集部署後需要實現session共享,針對 tomcat 伺服器的實現方案多種多樣,比如 tomcat cluster
session 廣播、nginx IP hash策略、nginx sticky module等方案,本文主要介紹了使用 redis
伺服器進行 session 統一儲存管理的共享方案。

相關應用結構參照下圖:

二、環境配置

系統:Centos7
tomcat:apache-tomcat-7.0.78
redis:redis-2.8.9

三、構建 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:[email protected]: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 '[email protected]' url 'https://github.com/jcoleman' } } } } } }

4、執行gradle命令構建原始碼,編譯輸出tomcat-redis-session-manager-master 及依賴jar包

gradle build -x test  copyJars

檔案列表如下:

四、tomcat 配置

兩臺tomcat伺服器分別在不同的虛擬機器上,地址:

http://192.168.31.84:8080
http://192.168.31.82:8080

五、編寫測試頁面

在tomcat安裝目錄下webapps/ROOT/新增test.jsp檔案,內容為:

<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false"%>
 SessionID:<%=session.getId()%><BR>
 SessionIP:<%=request.getServerName()%> <BR>
 SessionPort:<%=request.getServerPort()%>
 <%     out.println("This is Tomcat Server 82(根據情況修改,以便區別) !");     %>

六、tomcat session manager 配置

1.新增commons-pool2-2.2、jedis-2.5.2、tomcat-redis-session-manager-master-2.0.0jar包到tomcat 安裝目錄的 lib 資料夾;
2.修改兩臺tomcat的context.xml檔案,使 tomcat-redis-session-manager-master 作為session管理器,同時指定redis地址和埠。

context.xml配置:

<Context>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

   <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
   <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
           host="192.168.31.84"
           port="6379"
           database="0"
           maxInactiveInterval="60" />
</Context>

3.重啟兩臺tomcat

七、nginx 配置

1.修改nginx.conf檔案,內容如下:

#user  nobody;
worker_processes  1;

events {
    worker_connections  1024;
}

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

    sendfile        on;
    keepalive_timeout  65;

    upstream tomcat_nginx {
        server localhost:8080;
        server 192.168.31.82:8080;
    }

    server {
        listen       80;
        server_name  localhost;
        location / {
            proxy_pass http://tomcat_nginx;
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2.重啟nginx:

nginx -s reload

八、測試

nginx預設採用輪詢的方式進行負載均衡,重新整理頁面: