---
title: "利用nginx+tomcat+memcached组建web服务器负载均衡 "
author: "wuce7758"
date: "2013-01-14T11:41:53Z"
tags: []
categories: ["企业架构"]
slug: "nginx-tomcat-memcached-web"
draft: false
lastmod: "2013-01-14T11:41:53Z"
id: 1769310
url: "https://wuce7758.iteye.com/blog/1769310"
---

## 1 起因

    最近对新开发的web系统进行了压力测试，发现tomcat默认配置下压到600人的并发登录首页响应速度就有比较严重的影响，一轮出现2000多个的500和502错误。我把登录的时间统计做了一下，把服务器处理总时间打印出来，看了一下发现有个别响应确实在20秒，但平均时间和lr测试出来的还是相差很远。所以可以断定不是程序处理处理花费了这么多时间，由于在局域网测试，所以也可以排除网络问题。这就把问题圈定在tomcat的请求响应能力上了。先把tomcat线程数提升到1000，发现500和502的报错降到几十个，但是响应时间上还没什么提高。后来启动了2个tomcat，用nginx做负载均衡，响应时间下降了40%，两个tomcat的处理时长都保持在1秒左右。

    看来tomcat性能确实是系统的一个瓶颈，很有必要假设多个服务器来加强响应能力。之前由于只是测试登录，多个tomcat还不用共享session，但真正使用时是必须要能一起工作的。现记录一下负载均衡的安装配置过程。

 

## 2 解决方案的选择

    多个tomcat要一起协同工作有几种办法，可以考虑的方案有以下几个：

  1. 使用tomcat自带的cluster方式，多个tomcat见自动实时复制session信息，配置起来很简单。但这个方案的效率比较低，在大并发下表现并不好。

  2. 利用nginx的基于访问ip的hash路由策略，保证访问的ip始终被路由到同一个tomcat上，这个配置更简单。但是我们的应用很可能是某一个局域网大量用户同时登录，这样负载均衡就没什么作用了。

  3. 利用memcached把多个tomcat的session集中管理，这是最直接的解决方案，但是操作起来也最为复杂。

    我们的系统既要求性能，又要比较好的利用上负载均衡，所以第3个方案是首选。接下来就是安装搭建之路了。

## 3 安装配置

### **3.1 memcached的安装**

  1）先下载libevent-1.4.14b-stable.tar.gz和memcached-1.4.7.tar.gz的源码包，前者是后者的依赖包，就是一个事件驱动的包。

  2）安装非常顺利，还是经典的那几个编译安装命令：

 

Linux代码 [![复制代码](http://isoftyh.iteye.com/images/icon_copy.gif)](http://isoftyh.iteye.com/blog/1748597 "复制代码") [![收藏代码](http://isoftyh.iteye.com/images/icon_star.png)![](http://isoftyh.iteye.com/images/spinner.gif)]()

01. tar zxvf libevent-1.4.14b-stable.tar.gz
02. cd libevent-1.4.14b-stable
03. ./configure --prefix=/usr/local/libevent-1.4.14b
04. make
05. make install
06. tar zxvf memcached-1.4.7.tar.gz
07. cd memcached-1.4.7
08. ./configure --prefix=/usr/local/memcached-1.4.7 --with-libevent=/usr/local/libevent-1.4.14b/
09. make
10. make install

```
tar zxvf libevent-1.4.14b-stable.tar.gz 

cd libevent-1.4.14b-stable 

./configure --prefix=/usr/local/libevent-1.4.14b 

make 

make install 

tar zxvf memcached-1.4.7.tar.gz 

cd memcached-1.4.7 

./configure --prefix=/usr/local/memcached-1.4.7 --with-libevent=/usr/local/libevent-1.4.14b/ 

make 

make install 
```

 

 

  3）启动memcached：

  ./bin/memcached -d -m 256 -u root -p 11211 -c 1024 -P /tmp/memcached.pid

 

### **3.2 memcached-session-manager配置**

    让tomcat调用memcached来存储session早就是一个很成熟的解决方案了，开源的msm就可以解决这个问题。比较折腾的就是要用到的jar包，官方文档说的也比较含糊，我这里用的是kryo的序列化方案，所以用到的包多一些，分别是：

kryo-1.03.jar

kryo-serializers-0.8.jar 

memcached-2.5.jar（我在官方看最新已经到2.7了，但是msm官方说用2.5，可能新包没测试过，特别是2.6版本changelog里面提到api有调整，还是不要乱升的好）

memcached-session-manager-1.5.1.jar

memcached-session-manager-tc7-1.5.1.jar

minlog-1.2.jar

msm-kryo-serializer-1.5.1.jar

reflectasm-0.9.jar

    以上这些包都放在$CATALINA\_HOME/lib目录下。

    另外提一下，官方给出的4种序列化方案，其中kryo是效率最高的，具体比较看http://code.google.com/p/memcached-session-manager/wiki/SerializationStrategies。

    接下来是修改tomcat的配置文件$CATALINA\_HOME/conf/context.xml，调整成新的session存储方式。配置文件中加入以下内容：

 

Xml代码 [![复制代码](http://isoftyh.iteye.com/images/icon_copy.gif)](http://isoftyh.iteye.com/blog/1748597 "复制代码") [![收藏代码](http://isoftyh.iteye.com/images/icon_star.png)![](http://isoftyh.iteye.com/images/spinner.gif)]()

1. **&lt;Manager** className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
2. memcachedNodes="n1:127.0.0.1:11211"
3. sticky="false"
4. lockingMode="auto"
5. sessionBackupAsync="false"
6. sessionBackupTimeout="1000"
7. transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"
8. **/&gt;**

```
 <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager" 

      memcachedNodes="n1:127.0.0.1:11211" 

      sticky="false" 

      lockingMode="auto" 

      sessionBackupAsync="false"   

      sessionBackupTimeout="1000"  

      transcoderFactoryClass="de.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory" 

      /> 
```

 

 

    在$CATALINA\_HOME/conf/logging.properties文件中添加de.javakaffee.web.msm.level=FINE，就可以在catalina.out的日志中看到详细的session存取情况。

    另外在Manager配置中加上requestUriIgnorePattern=".\*\\.(png|gif|jpg|css|js)$"，用chrome浏览器测试发现居然sessionID会突然变掉，然后就被拦截器给跳回首页了。去掉就一切正常，但拦截器只会去检测action的，按理说应该完全没关系，望高人指点！

### **3.3 nginx配置**

    nginx非常简单，只要在upstream里面多配置几个server就可以了，这里把我的配置贴出来：#user nobody; 

Linux代码 [![复制代码](http://isoftyh.iteye.com/images/icon_copy.gif)](http://isoftyh.iteye.com/blog/1748597 "复制代码") [![收藏代码](http://isoftyh.iteye.com/images/icon_star.png)![](http://isoftyh.iteye.com/images/spinner.gif)]()

01. worker\_processes  16;
02. events {
03. use epoll;
04. worker\_connections  65535;
05. }
06. http {
07. include       mime.types;
08. default\_type  application/octet-stream;
09. #log\_format  main  '$remote\_addr - $remote\_user \[$time\_local] "$request" '
10. #                  '$status $body\_bytes\_sent "$http\_referer" '
11. #                  '"$http\_user\_agent" "$http\_x\_forwarded\_for"';
12. #access\_log  logs/access.log  main;
13. client\_header\_buffer\_size 32k;
14. large\_client\_header\_buffers 4 32k;
15. client\_max\_body\_size 8m;
16. client\_body\_buffer\_size 128k;
17. sendfile        on;
18. tcp\_nopush     on;
19. #keepalive\_timeout  0;
20. keepalive\_timeout  65;
21. gzip  on;
22. gzip\_types       text/javascript text/plain text/css application/xml application/x-javascript;
23. gzip\_disable     "MSIE \[1-6]\\.(?!.\*SV1)";
24. proxy\_connect\_timeout 300;
25. proxy\_send\_timeout 300;
26. proxy\_read\_timeout 300;
27. proxy\_buffer\_size 16k;
28. proxy\_buffers 4 32k;
29. proxy\_set\_header X-Forwarded-For $remote\_addr;
30. proxy\_set\_header Connection Close;
31. server\_names\_hash\_max\_size 1024;
32. server\_names\_hash\_bucket\_size 1024;
33. # Default cache parameters for use by virtual hosts
34. # Set the cache path to tmpfs mounted disk, and the zone name
35. # Set the maximum size of the on disk cache to less than the tmpfs file system size
36. proxy\_cache\_path  ./cache  levels=1:2  keys\_zone=pscms:100m max\_size=800m;
37. proxy\_temp\_path   ./proxy;
38. #配置后端服务器信息
39. upstream web\_server {
40. #ip\_hash;
41. server localhost:8080 max\_fails=3  fail\_timeout=30s;
42. server localhost:8180 max\_fails=3  fail\_timeout=30s;
43. }
44. server {
45. listen   8888; ## listen for ipv4
46. #listen   \[::]:80 default ipv6only=on; ## listen for ipv6
47. server\_name  localhost;
48. charset utf-8;
49. log\_format  main  '$remote\_addr - $remote\_user \[$time\_local] "$request" '
50. '$status $body\_bytes\_sent "$http\_referer" '
51. '"$http\_user\_agent" "$http\_x\_forwarded\_for"';
52. access\_log  logs/host.access.log  main;
53. #access\_log off;
54. location ~ .\*\\.(jsp|action)?$ {
55. proxy\_set\_header Host $http\_host;
56. proxy\_redirect     off;
57. proxy\_pass         http://web\_server;
58. proxy\_set\_header   Host             $host;
59. proxy\_set\_header   X-Real-IP        $remote\_addr;
60. proxy\_set\_header   X-Forwarded-For $proxy\_add\_x\_forwarded\_for;
61. }
62. location ~ .\*\\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ {
63. #如果后端的服务器返回502、504、执行超时等错误，自动将请求转发到upstream负载均衡池中的另一台服务器，实现故障转移。
64. proxy\_next\_upstream http\_502 http\_504 error timeout invalid\_header;
65. proxy\_cache pscms;                   #进行缓存，使用Web缓存区cache\_one
66. proxy\_cache\_valid 200 304 1h;           #对不同的HTTP状态码设置不同的缓存时间
67. proxy\_cache\_valid 301 302 5m;
68. proxy\_cache\_valid any 1m;
69. proxy\_set\_header  Host $host;
70. proxy\_set\_header  X-Real-IP  $remote\_addr;
71. proxy\_set\_header X-Forwarded-For $remote\_addr;
72. proxy\_set\_header Accept-Encoding "";  #（或是后台服务器关闭gzip），这样这台机器才不会缓存被压缩的文件，造成乱码
73. proxy\_ignore\_headers "Cache-Control" "Expires"; #这段配置加上后，proxy\_cache就能支持后台设定的expires。
74. proxy\_pass http://web\_server;
75. expires  15m;
76. }
77. location / {
78. proxy\_set\_header Host $http\_host;
79. proxy\_redirect     off;
80. proxy\_pass         http://web\_server;
81. proxy\_set\_header   Host             $host;
82. proxy\_set\_header   X-Real-IP        $remote\_addr;
83. proxy\_set\_header   X-Forwarded-For $proxy\_add\_x\_forwarded\_for;
84. }
85. }
86. }

```
worker_processes  16; 

events { 

    use epoll; 

    worker_connections  65535; 

} 

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; 
 
    client_header_buffer_size 32k; 

    large_client_header_buffers 4 32k; 

    client_max_body_size 8m; 

    client_body_buffer_size 128k; 

    sendfile        on; 

    tcp_nopush     on; 

 

    #keepalive_timeout  0; 

    keepalive_timeout  65; 

 

    gzip  on; 

    gzip_types       text/javascript text/plain text/css application/xml application/x-javascript;

    gzip_disable     "MSIE [1-6]\.(?!.*SV1)"; 

 

    proxy_connect_timeout 300; 

    proxy_send_timeout 300; 

    proxy_read_timeout 300; 

    proxy_buffer_size 16k; 

    proxy_buffers 4 32k; 

 

    proxy_set_header X-Forwarded-For $remote_addr; 

    proxy_set_header Connection Close; 

    server_names_hash_max_size 1024; 

    server_names_hash_bucket_size 1024; 

 

    # Default cache parameters for use by virtual hosts 

    # Set the cache path to tmpfs mounted disk, and the zone name 

    # Set the maximum size of the on disk cache to less than the tmpfs file system size 

    proxy_cache_path  ./cache  levels=1:2  keys_zone=pscms:100m max_size=800m; 

    proxy_temp_path   ./proxy; 

 

    #配置后端服务器信息 

    upstream web_server { 

        #ip_hash; 

        server localhost:8080 max_fails=3  fail_timeout=30s; 

        server localhost:8180 max_fails=3  fail_timeout=30s; 

    } 

 

    server { 

        listen   8888; ## listen for ipv4 

        #listen   [::]:80 default ipv6only=on; ## listen for ipv6 

        server_name  localhost; 

 

        charset utf-8; 

        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/host.access.log  main; 

        #access_log off; 

 

        location ~ .*\.(jsp|action)?$ { 

            proxy_set_header Host $http_host; 

            proxy_redirect     off; 

            proxy_pass         http://web_server; 

            proxy_set_header   Host             $host; 

            proxy_set_header   X-Real-IP        $remote_addr; 

            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for; 

        } 

 

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ { 

            #如果后端的服务器返回502、504、执行超时等错误，自动将请求转发到upstream负载均衡池中的另一台服务器，实现故障转移。 

            proxy_next_upstream http_502 http_504 error timeout invalid_header; 

 

            proxy_cache pscms;                   #进行缓存，使用Web缓存区cache_one 

            proxy_cache_valid 200 304 1h;           #对不同的HTTP状态码设置不同的缓存时间 

            proxy_cache_valid 301 302 5m; 

            proxy_cache_valid any 1m; 

            proxy_set_header  Host $host; 

            proxy_set_header  X-Real-IP  $remote_addr; 

            proxy_set_header X-Forwarded-For $remote_addr; 

            proxy_set_header Accept-Encoding "";  #（或是后台服务器关闭gzip），这样这台机器才不会缓存被压缩的文件，造成乱码 

            proxy_ignore_headers "Cache-Control" "Expires"; #这段配置加上后，proxy_cache就能支持后台设定的expires。 

            proxy_pass http://web_server; 

            expires  15m; 

        } 

 

        location / { 

            proxy_set_header Host $http_host; 

            proxy_redirect     off; 

            proxy_pass         http://web_server; 

            proxy_set_header   Host             $host; 

            proxy_set_header   X-Real-IP        $remote_addr; 

            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for; 

        } 

    } 

} 
```

 

   以上转载 http://passover.blog.51cto.com/2431658/648182

 

   关于多tomcat之间的session共享问题，我们的实现是放弃了使用session，通过写cookie的方式，在过滤器中检测是否有相应的cookie，然后放入到request里面。后来发现再多个环境切换的时候，会出现混乱。进而使用过了ThreadLocal,如果有相应的cookie，则将数据放入ThreadLocal中，而ThreadLocal为每一个线程都提供了变量的副本，使得每个线程在某一时间访问到的并不是同一个对象，这样就隔离了多个线程对数据的数据共享。