环境
操作系统:windows
tomcat1:Apache Tomcat/7.0.52(8085)
tomcat2:Apache Tomcat/7.0.52(8086)
jre:1.7.0_80
nginx:nginx-1.20.1(8070)
redis:Redis 3.0.501(6379)
说明
基于redis实现的session共享,基于nginx实现的负载均衡和反向代理。
部署
- session共享配置
1、拷贝相关jar包到所有tomcat的lib目录下
commons-pool2-2.2.jar
jedis-2.5.2.jar
tomcat-redis-session-manager-2.0.0.jar
2、编辑tomcat/conf/server.xml,修改内部的端口配置,保证端口号不会被重复使用(多服务器时端口可相同)
<Server port="8015" shutdown="SHUTDOWN">
<Service name="Catalina">
<Connector
port="8085"
protocol="HTTP/1.1"
redirectPort="8443"/>
</Service>
</Server>
3、编辑tomcat/conf/context.xml,在Context标签内增加内容如下:
<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
host="127.0.0.1"
port="6379"
database="0"
maxInactiveInterval="60" />
说明:Manager 标签内的host和port等信息为redis组件的信息
- 反向代理和负载均衡配置
1、在nginx/conf/nginx.conf文件中进行配置
可参考如下(包含反向代理和负载均衡):
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream web-01 {
server 192.168.0.168:8085 weight=1;
server 192.168.0.168:8086 weight=1;
}
server {
listen 8070;
server_name localhost;
location / {
root html;
index index.html index.htm;
proxy_pass http://web-01;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
- tomcat测试资源
部署test.jsp到测试包内
test.jsp内容参考如下(title和h1的内容可根据不同的tomcat进行调整以方便观察):
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>tomcat1</title>
</head>
<body>
<center><h1>tomcat1</h1></center>
<center>
<h3>sessionId:</h3><%=session.getId()%>
<h3>session创建时间:</h3><%=session.getCreationTime()%>
<center>
</body>
</html>
启动
- 双击nginx/nginx.exe启动
- 双击redis/redis-server.exe启动
- 双击tomcat/bin/start.bat启动多个tomcat
测试
-
浏览器输入test.jsp所在资源的路径,页面中会包含tomcat信息和sessionId信息
-
请求地址的ip和port为nginx代理的
-
可以观察到nginx会将多次请求进行负载均衡转发到不同的tomcat上,同时所有tomcat的sessionId是同一个,这个sessionId也可以在redis中看到
-
效果图:
-
redis内: