一、Nginx安装
详见前文:http://www.cnblogs.com/yixiwenwen/p/3574097.html
二、memcached安装和启动
详见前文:http://www.cnblogs.com/yixiwenwen/p/3574137.html
三、配置Nginx实现Tomcat的负载均衡和利用memcached实现session共享
1. 修改nginx的配置文件nginx.conf
user nobody; worker_processes 4; error_log logs/error.log; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; gzip on; upstream www.yixi.com { server 192.168.137.46:100; server 192.168.137.46:101; server 192.168.137.46:102; } server { listen 80; server_name www.yixi.com; charset utf-8; location / { root html; index index.html index.htm; proxy_pass http://www.yixi.com; proxy_set_header X-Real-IP $remote_addr; client_max_body_size 100m; } location ~ ^/(WEB-INF)/ { deny all; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
2. Tomcat配置
下载并解压三个tomcat7;
下载相应的jar包到所有的tomcat的lib目录下:
couchbase-client-1.2.2.jar
javolution-5.4.3.1.jar
memcached-session-manager-1.6.4.jar
memcached-session-manager-tc7-1.6.4.jar
msm-javolution-serializer-1.6.4.jar
msm-kryo-serializer-1.6.4.jar
msm-xstream-serializer-1.6.4.jar
spymemcached-2.10.2.jar
下面修改Tomcat配置文件,让Tomcat结合memcached实现session共享
[root@localhost lib]# vi /usr/local/tomcat/conf/context.xml
在配置文件中的<context></context>标签里面加入如下内容:
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager" memcachedNodes="n1:localhost:11211" requestUriIgnorePattern=".*\.(png|gif|jpg|css|js)$" sessionBackupAsync="false" sessionBackupTimeout="100" transcoderFactoryClass="de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoderFactory" copyCollectionsForSerialization="false" />
为了测试在tomcat默认的webroot下的index.jsp中加入这些代码:
SessionID:<%=session.getId()%> <BR> SessionIP:<%=request.getServerName()%> <BR> SessionPort:<%=request.getServerPort()%> <% out.println("This is Tomcat Server 111111!"); %>
(备注:当要同时启动多个tomcat时需要修改一些配置
a.修改/etc目录下的profile文件:
export CATALINA_HOME_test_1=/usr/local/tomcat_test/apache-tomcat-7-1 export CATALINA_HOME_test_2=/usr/local/tomcat_test/apache-tomcat-7-2 export CATALINA_HOME_test_3=/usr/local/tomcat_test/apache-tomcat-7-3
b.修改bin下的startup.sh和shutdown.sh
添加 export CATALINA_HOME=$CATALINA_2_HOME 利用profile中第二组设置
)
4.测试结果:
分别启动nginx memcached tomcat
将host的文件中映射www.yixi.com到自己的ip;
在浏览器中访问www.yixi.com
访问的的是tomcat3 此时sessionID是:598EA38832CA14F8F14AC3EF0276AD3D-n1
刷新几次发现访问的还是tomcat3,
为了测试 先杀死tomcat3的进程!
再刷新...
发现当tomcat3挂掉之后 请求就到了tomcat1 并且我们希望的sessionId还是598EA38832CA14F8F14AC3EF0276AD3D-n1
再把tomcat1挂掉试试:
测试结果:
只剩下tomcat2还能用 而且sessionId是共享的。
这样整个配置和测试就完成了
附件:
tomcat部分:http://download.csdn.net/detail/yixiwenwen/6986845
nginx.conf :http://download.csdn.net/detail/yixiwenwen/6986719
参考:
https://github.com/magro
https://github.com/magro/memcached-session-manager/tree/memcached-session-manager-project-1.8.3
https://code.google.com/p/memcached-session-manager/wiki/SetupAndConfiguration