Linux: CentOS 7 64位系统
Nginx: 版本1.9.5
Tomcat: 版本7.0
Redis: 3.0.4css
使用nginx作负载均衡, 2台tomcat应用服务器, 使用redis统一存储session
准备2台linux服务器html
服务器A: ip 192.168.186.128 用于安装nginx(端口80)和tomcat1(端口8080)
服务器B: ip 192.168.186.129 用于安装tomcat2(端口8080)和redis(端口6379)java
本文着重介绍负载均衡,应用集群配置以及解决session共享问题, 而对于nginx, tomcat, redis的安装将略过linux
nginx配置:
修改nginx.conf文件
user www;
worker_processes 1; 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 tomcat.com { server localhost:8080 max_fails=3 weight=1 fail_timeout=60s; server 192.168.186.129:8080 max_fails=3 weight=3 fail_timeout=60s; } server { listen 80; server_name localhost; charset utf-8; location / { root /alidata/www; index index.html index.htm; } #将全部动态请求(即以jsp结尾的请求转发tomcat服务器) location ~ .*.jsp$ { index index.jsp; proxy_pass http://tomcat.com; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 1h; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
server localhost:8080 max_fails=3 weight=1 fail_timeout=60s;
max_fails: 最大的失败链接数, 即当链接此服务器3次都失败时, nginx则将不会再转发请求至这台服务器上
weight: 即权重, 数值越大则分配的请求将会越多,
fail_timeout: 链接失败的超时时间, 即超过指定时间还未链接成功,就会将请求转发至其余服务器nginx
添加如下3个jar文件到tomcat的lib目录中(用于tomcat服务器session保存至redis数据库, 实现session共享):redis
tomcat-redis-session-manager-1.2-tomcat-7-java-7.jar
jedis-2.0.0.jar
commons-pool-1.5.5.jar数据库
点击下载tomcat
修改两个tomcat服务器conf目录下context.xml文件, 在节点中添加以下配置:服务器
session
<Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<Manager className="com.radiadesign.catalina.session.RedisSessionManager"
host="192.168.186.129"
port="6379"
database="0"
maxInactiveInterval="60" />
链接参数请改成您的实际环境中的参数。
在tomcat1的应用访问根目录下新建jsp,在body中添加以下代码:
<% session.setAttribute("name", "tomcat1"); %> success access tomcat1; 在tomcat1的session中存入key为name, value为tomcat1的记录 一样在tomcat2的应用访问根目录下新建jsp,在body中添加以下代码: <% String name = (String) session.getAttribute("name"); %> success access tomcat2;<br/> <%=name %>
依次启动reids, tomcat1, tomcat2, nginx
访问http://192.168.186.128/index.jsp
会发现页面均匀的显示
success access tomcat1;
success access tomcat2;
而且查看redis数据库时会发现, 有session信息存入redis数据库
至此, 配置成功! 此案例仅用于介绍负载均衡,应用集群配置以及解决session共享问题, 而实际应用中, 还须要对nginx, tomcat, redis等进行配置优化以达到最佳性能, 此处不做详细说明, 有兴趣能够一块儿讨论