服务器清单:
192.168.10.1 tomcat1
192.168.10.2 tomcat2
192.168.10.3 redis
192.168.10.4 nginx
一、背景
在使用Nginx+Tomcat实现负载均衡的时候,由于Nginx对不同的请求分发到某一个Tomcat,Tomcat在运行的时候分别是不同的容器里,因为会出现session不同步或者丢失的问题。
二、Nginx安装与配置
1、Nginx安装
网上的资源对于安装Nginx的介绍比较多,例如最简单的为:
(1) 获取nginx,在http://nginx.org/download/上可以获取当前最新的版本下载,例如:wget http://nginx.org/download/nginx-1.9.8.tar.gz
(2)解压缩 tar -xvf nginx-1.9.8.tar.gz包。
(3)进入解压缩目录,执行./configure --prefix=/usr/local/nginx-1.9.8 将Nginx安装到/usr/local/nginx-1.9.8目录下
(4)make & make install
安装的过程会将Nginx安装到/usr/local/nginx-1.9.8目录下,启动Nginx测试是否可以正常启动。
2、修改Nginx配置多Tomcat服务器
2.1、修改conf/nginx.conf文件,在server标签上边添加upstream如下:
upstream myserver{
#weigth参数表示权值,权值越高被分配到的几率越大
server 192.168.10.1:8080 weight=1;
server 192.168.10.2:8080 weight=1;
}
这里指定了本机下的两个Tomcat实例,端口分别为8080,8080,权重都为1,后边配置Tomcat实例,myserver这个是自己随意命名的,下边要用到
2.2、配置server标签;
server {
listen 80;
server_name 192.168.1.149;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
# root html;
# index index.html index.htm;
proxy_pass http:
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
2.3、配置之后的完整内容如下(1.9.8版本删去了注释后的配置内容):
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream mynginxserver {
server 192.168.10.1:8080 weight=1;
server 192.168.10.2:8080 weight=1;
}
server {
listen 80;
server_name 192.168.10.4;
location / {
proxy_pass http://mynginxserver;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
重启nginx
#service nginx restart
3、将tomcat-redis-session-1.0-SNAPSHOT.jar、jedis-2.7.2.jar、commons-pool2-2.0.jar 三个jar包分别放在tomcat1和tomcat2实例下的lib目录下。
免费下载这三个jar:http://download.youkuaiyun.com/detail/u010870518/9585716
注意:
如果项目里面已经采用了redis缓存,注意jedis的jar包的版本问题,保持jedis的jar版本和项目中一致
4、修改tomcat实例下conf/contex.xml文件
<?xml version='1.0' encoding='utf-8'?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
host="192.168.1.3"
port="6379"
database="0"
maxInactiveInterval="1800" />
</Context>
如果Redis配置了访问权限,请添加密码为:
<?xml version='1.0' encoding='utf-8'?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
host="192.168.1.3"
port="6379"
database="0"
password="redispassword"
maxInactiveInterval="1800" />
</Context>
注意maxInactiveInterval="1800",因为tomcat的session失效时间是30分钟。所以redis的缓存时间设置为1800s;至此,配置完成,可以访问192.168.10.4看看多次刷新效果,登录后访问不同页面效果。这里效果不再说明。