(一) nginx配置tomcat集群
1.配置nginx.cnf文件如下:
server {
listen 80 default_server; server_name _;
return 444; #過濾其他域名的請(qǐng)求,返回444狀態(tài)碼
}
server {
listen 80;
server_name wx.ppp.com; # www.aaa.com域名
location /
{
proxy_pass http://wx.ppp.com;
# proxy_pass http://localhost:8088; # 對(duì)應(yīng)端口號(hào)8088
#proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
#proxy_ignore_headers Set-Cookie;
#proxy_hide_header Set-Cookie;
#proxy_hide_header X-powered-by;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header Host $http_host;
expires 10m;
}
}
#服務(wù)器的集群
upstream wx.ppp.com { #服務(wù)器集群名字
server 127.0.0.1:8088 weight=1;#服務(wù)器配置 weight是權(quán)重的意思,權(quán)重越大,分配的概率越大。
server 127.0.0.1:38088 weight=1;
}
(二)配置tomcat 與 redis session共享
1、安裝redis
下載:wget -q http://download.redis.io/releases/redis-3.2.1.tar.gz
解壓:tar -xzf redis-3.2.1.tar.gz
切換目錄 cd ./redis-3.2.1
編譯:make
安裝:make install
運(yùn)行:src/redis-server
2、 添加以下jar包:
tomcat85-session-redis-1.0.jar
jedis-2.9.0.jar
commons-pool2-2.4.2.jar
3、分別修改集群中tomcat的 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" />
4、重啟tomcat ,若啟動(dòng)正常則配置成功。
5、瀏覽器中分別訪問集群tomcat 中的頁面,觀察sessionid 是否一致。
6、創(chuàng)建讀寫session jsp,一個(gè)用來寫session,一個(gè)用來讀session。
read.jsp讀取session中的 userId
<%@ 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>Read session</title>
</head>
<body>
Server : Server 1 (因需將頁面部署在不同Tomcat,以測(cè)試能讀取另一臺(tái)Tomcat設(shè)置的Session,請(qǐng)自行設(shè)服務(wù)器標(biāo)識(shí))<br />
<%=request.getSession().getAttribute("userId")%>
</body>
</html>
write.jsp寫入userId到session中
<%@ page import="java.util.Date"%>
<%@ 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>Write session</title>
</head>
<body>
Server : Server 1 (因需將頁面部署在不同Tomcat,以測(cè)試能讀取另一臺(tái)Tomcat設(shè)置的Session,請(qǐng)自行設(shè)服務(wù)器標(biāo)識(shí))<br />
Write session
<%
request.getSession().setAttribute("userId", new Date().getTime());
%>
</body>
</html>
分別將兩個(gè)jsp文件放到tomcat中,在其中的一個(gè)tomcat中運(yùn)行 write.jsp寫入userId。然后其他tomcat中運(yùn)行 read.jsp查看userId的值,發(fā)現(xiàn)會(huì)讀取到第一個(gè)頁面寫入的userId,并且和其他tomcat中讀取的值一致。大功告成!
注:tomcat85-session-redis-1.0.jar下載地址:http://download.csdn.net/download/wjwj1203/9934717