环境
操作系统:windows
tomcat1:Apache Tomcat/7.0.52(8085)
tomcat2:Apache Tomcat/7.0.52(8086)
jdk:1.8.0_251
nginx:nginx-1.20.1(8070)
memcache:1.4.4-14-g9c660c0(11211)
说明
基于memcache实现的session共享,基于nginx实现的负载均衡和反向代理。
部署
- session共享配置
1、拷贝相关jar包到所有tomcat的lib目录下
memcache.zip
2、编辑tomcat/conf/server.xml,修改内部的端口配置,保证端口号不会被重复使用(多服务器时端口可相同),Engine标签内增加jumRoute配置(多个tomcat配置不同)
<Server port="8015" shutdown="SHUTDOWN"> <Service name="Catalina"> <Connector port="8085" protocol="HTTP/1.1" redirectPort="8443"/> </Service> <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1"> </Engine> </Server>
3、编辑tomcat/conf/context.xml,在Context标签内增加内容如下:
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager" memcachedNodes="n1:127.0.0.1:11211" requestUriIgnorePattern=".*\.(png|gif|jpg|css|js)$" sessionBackupAsync="false" sessionBackupTimeout="3000" transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" copyCollectionsForSerialization="false" />
说明:Manager 标签内的memcachedNodes信息为memcache组件的信息
- 反向代理和负载均衡配置
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启动
- cmd管理员模式进入到memcache安装路径下,执行命令memcached.exe -d start启动,可在服务中查看是否启动成功
- 双击tomcat/bin/startup.bat启动多个tomcat
测试
- 浏览器输入test.jsp所在资源的路径,页面中会包含tomcat信息和sessionId信息
请求地址的ip和port为nginx代理的
- 可以观察到nginx会将多次请求进行负载均衡转发到不同的tomcat上,同时所有tomcat的sessionId是同一个