【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享

摘要:
由于需要实现负载平衡,所以它不能是单个服务器。这里提到的服务器是由我们配置的Tomcat服务器,它们是两个以上的Tomcat服务器#usernobody;工人进程1;#error_loglogs/error。日志;#error_loglogs/error。日志通知;#error_loglogs/error。登录信息;#pidlogs/nginx。pid;事件{worker_connections1024;}http{includeme.types;default_typeapplication/octet stream;#log_formain‘$remote_addr-$remote_user[$time_local]“$request”‘#‘$status$body_bytes_send“$http_referer”‘#’“$http_user_agent”“$http_x_forwarded for”‘;#access_logloggs/access.logmain;sendfileon;#tcp_nopushon;#keepalive_timeout0;keepalive_timeout65;#gzipon;server{listen80;server_namelocalhost;#charsetkoi8-r;#access_loglogs/host.access.logmain;location/{代理连接超时3;代理发送超时30;代理读取超时30passhttp://clustername ;}# error_ page404/404.html;#重定向服务器错误页面至静态页面/50x。html#error_page500502503504/50x。html;位置=/50x。html{roothtml;}#proxithePHPscriptstoApachelisteningon127.0.0.1:80##位置~。php${#proxypasshttp://127.0.0.1 ;#}# 将HP脚本传递给fastcgi服务器列表127.0.0.1:9000##位置~.php${#roothtml;#fastcgi_pass127.0.0.1:9;#fastcgi_index.php;#fastcci_paramSCRIPT_FILENAME/scripts$fastcgi_script_name;#includefastcgi_params;#}#访问.htaccessfile,如果Apache的documentroot#与nginx的一个##位置~/一致。Ht{#denyall;#}}#另一个虚拟主机使用IP-,name-,和基于端口的配置##服务器{#listen8000;#listenhomename:8080;#server_nameamemenaisanoother.alias;#location/{#roothtml;#indexindex.html;#}##}#集群配置:服务器列表上游集群名称{serverwww.a.com:8080weight=1;#服务器配置权重表示权重。权重越大,分配的可能性越大。}localhost是集群的名称,weight表示权重。权重越大,分配给的概率越大。3.max _ Failures:允许失败的请求数为1。超过最大值时,将返回代理。next_上游模块定义中的错误4.fail _ timeout:max_失败后暂停的时间。Nginx支持同时设置多组负载平衡,用于

  今天想着将项目优化一下,就想的实现集群分布,在本机测试:利用nginx+tomcat实现

  通过上一篇博客(http://www.cnblogs.com/qlqwjy/p/8535235.html),Nginx就算是可以运行了,但是如何与Tomcat结合,实现负载均衡呢?既然要实现负载均衡,那肯定不是一个服务器,这里说的服务器是我们自己配置的Tomcat服务器,而且是两台tomcat以上。接下来开始搭建环境:

 1.在电脑中配置多个域名,模仿多个主机

    (1)在系统配置文件C:WindowsSystem32driversetchosts中将本机IP和域名做绑定

      【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第1张

    (2)启动nginx测试域名:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第2张

 【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第3张

2.配置两台tomcat(修改server.xml中的配置,两台tomcat具有不同的端口)

 (1)第一台使用Tomcat7,且使用默认的8080端口,域名使用虚拟的www.a.com

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第4张

启动后测试:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第5张

 (2)第二台使用Tomcat8,而且使用8081端口,域名使用www.b.com:

 【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第6张

3.配置好Tomcat服务器之后,要实现通过Nginx来反向代理,那么此时就需要修改Nginx的配置文件,进去到Nginx目录,找到conf下的nginx.conf文件,用记事本打开。

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#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;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
               proxy_connect_timeout   3;
               proxy_send_timeout      30;
               proxy_read_timeout      30;
               proxy_pass http://clustername;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ .php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    
    
    
    #集群配置:服务器列表
    upstream clustername {
      server www.a.com:8080 weight=1;#服务器配置   weight是权重的意思,权重越大,分配的概率越大。
      server www.b.com:8081 weight=1;#服务器配置   weight是权重的意思,权重越大,分配的概率越大。
    }
    

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

 补充:

  这个配置有个问题,那就是没有配置哪些目录是不允许直接被访问的,在传统的tomcat做服务器的时候本身不允许访问WEB-INF下面的东西,防止class文件以及以下XML配置泄露,因此新版本在上面配置中增加了三行:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第7张

主要配置:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第8张

 【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第9张

    解释:

 (1)如下配置:

    #集群配置:服务器列表
    upstream clustername{
      server www.a.com:8080 weight=1;#服务器配置   weight是权重的意思,权重越大,分配的概率越大。
      server www.b.com:8081 weight=1;#服务器配置   weight是权重的意思,权重越大,分配的概率越大。
    }

  localhost是集群的名字,weight表示权重,权重越大,更多概率被分配到。

与weeight等价的参数配置:

每个设备的状态设置为:
  1.down 表示单前的server暂时不参与负载
  2.weight 默认为1.weight越大,负载的权重就越大。
  3.max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误
  4.fail_timeout:max_fails次失败后,暂停的时间。
  5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
  nginx支持同时设置多组的负载均衡,用来给不用的server来使用。
  client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug
  client_body_temp_path 设置记录文件的目录 可以设置最多3层目录
  location 对URL进行匹配。可以进行重定向或者进行新的代理 负载均衡

  (2)如下配置:

        location / {
               proxy_connect_timeout   3;
               proxy_send_timeout      30;
               proxy_read_timeout      30;
               proxy_pass http://clustername;
        }

  proxy_pass    http:/clustername中的clustername是集群的名字,与上面配置中集群名字一样

  

参考:    https://www.cnblogs.com/meet/p/6051781.html

    http://blog.csdn.net/mlc1218559742/article/details/53128382

  (3)测试:关闭nginx后重启测试:( 不停的刷新,发现Tomcat服务器不停的切换)

    【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第10张

 【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第11张

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第12张

4.  至此集群搭建初步完成了,在Tomcat中部署一web项目进行测试:

web项目只有一个index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    jsessionid=${pageContext.session.id}
    <br/>
    <%=request.getRealPath("/")%>
</body>
</html>

(1)tomcat7中与tomcat8中分别部署项目,如下:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第13张

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第14张

 (2)不通过nginx进行测试:(发现项目路径和SessionID都不同)

  • 访问tomcat7下面的项目:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第15张

  • 访问tomcat8下面的项目:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第16张

 (3) 通过nginx进行测试:(不停的刷新路径,发现项目路径和SessionID都不同,且服务器一次tomcat7,一次tomcat8)

 【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第17张

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第18张

  

5.为了解决上面的Session不同,需要实现ession共享(注意:不同版本的TomcatSession共享有问题,因此将上面的tomcat8改为Tomcat7

(1)将Tomcat8换为Tomcat7

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第19张

 【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第20张

bin目录下的catalina.bat和startup.bat两个文件。将两个文件中的CATALINA_HOME、CATALINA_BASE替换为我们设置的环境变量CATALINA_HOME1、CATALINA_BASE1

(2)配置Tomcat实现Session共享:

  •   修改两个Tomcat安装目录下面conf/server.xml,将集群配置放开:

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第21张

  •   修改项目中web.xml

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第22张

(3)测试:(服务器一直发生变化,SessionID未发生变化则表明session共享)

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第23张

【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享第24张

  至此,nginx+tomcat集群负载均衡+session共享已经简单实现。

剩余待解决的问题:

   集群的文件上传问题?集成redis实现Session共享(参考https://www.cnblogs.com/sunshine-2015/p/5686750.html)?如何整合memcached实现Session共享?

参考:http://blog.csdn.net/lifetragedy/article/details/7712691

  https://www.cnblogs.com/rocomp/p/4802396.html

(总结)Nginx配置文件nginx.conf中文详解

#定义Nginx运行的用户和用户组
user www www;
#nginx进程数,建议设置为等于CPU总核心数。
worker_processes 8;
#全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;
#进程文件
pid /var/run/nginx.pid;
#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。
worker_rlimit_nofile 65535;
#工作模式与连接数上限
events
{
    #参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
    use epoll;
    #单个进程最大连接数(最大连接数=连接数*进程数)
    worker_connections 65535;
}
#设定http服务器
http
{
    include mime.types; #文件扩展名与文件类型映射表
    default_type application/octet-stream; #默认文件类型
    #charset utf-8; #默认编码
    server_names_hash_bucket_size 128; #服务器名字的hash表大小
    client_header_buffer_size 32k; #上传文件大小限制
    large_client_header_buffers 4 64k; #设定请求缓
    client_max_body_size 8m; #设定请求缓
    sendfile on; #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。
    tcp_nopush on; #防止网络阻塞
    tcp_nodelay on; #防止网络阻塞
    keepalive_timeout 120; #长连接超时时间,单位是秒
    #FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    #gzip模块设置
    gzip on; #开启gzip压缩输出
    gzip_min_length 1k; #最小压缩文件大小
    gzip_buffers 4 16k; #压缩缓冲区
    gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
    gzip_comp_level 2; #压缩等级
    gzip_types text/plain application/x-javascript text/css application/xml;
    #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
    gzip_vary on;
    #limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用
    upstream blog.ha97.com {
        #upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。
        server 192.168.80.121:80 weight=3;
        server 192.168.80.122:80 weight=2;
        server 192.168.80.123:80 weight=3;
    }
    #虚拟主机的配置
    server {
        #监听端口
        listen 80;
        #域名可以有多个,用空格隔开
        server_name www.ha97.com ha97.com;
        index index.html index.htm index.php;
        root /data/www/ha97;
        location ~ .*.(php|php5)?$
        {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
        }
        #图片缓存时间设置
        location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires 10d;
        }
        #JS和CSS缓存时间设置
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }
        #日志格式设定
        log_format access '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" $http_x_forwarded_for';
        #定义本虚拟主机的访问日志
        access_log /var/log/nginx/ha97access.log access;
        #对 "/" 启用反向代理
        location / {
            proxy_pass http://127.0.0.1:88;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
            #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            #以下是一些反向代理的配置,可选。
            proxy_set_header Host $host;
            client_max_body_size 10m; #允许客户端请求的最大单文件字节数
            client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
            proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
            proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
            proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
            proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
            proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置
            proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
            proxy_temp_file_write_size 64k;
            #设定缓存文件夹大小,大于这个值,将从upstream服务器传
        }
        #设定查看Nginx状态的地址
        location /NginxStatus {
            stub_status on;
            access_log on;
            auth_basic "NginxStatus";
            auth_basic_user_file conf/htpasswd;
            #htpasswd文件的内容可以用apache提供的htpasswd工具来产生。
        }
        #本地动静分离反向代理配置
        #所有jsp的页面均交由tomcat或resin处理
        location ~ .(jsp|jspx|do)?$ {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:8080;
        }
        #所有静态文件由nginx直接读取不经过tomcat或resin
        location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
        { expires 15d; }
        location ~ .*.(js|css)?$
        { expires 1h; }
    }
}

免责声明:文章转载自《【nginx+tomcat集群】Nginx1.12.2+Tomcat7集群+负载均衡+Session共享》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Java向下转型的意义php Make编译PEAR package PHP_Archive not installed: generated phar will require PHP's phar extension be enabled.下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

k8s集群部分常见问题处理

目录部分常见问题处理 Coredns CrashLoopBackOff 导致无法成功添加工作节点的问题 添加工作节点时提示token过期 kubectl 执行命令报“The connection to the server localhost:8080 was refused” 网络组件flannel无法完成初始化 部分节点无法启动pod  最后  ...

1.初识nginx

​在一个遥远的乡村发生了一件事,村里的邮差老王要退休,同时宣布小张成为新一任的邮差,继续为村民服务。这里的村民生活的nginx帝国地域辽阔,人口众多。帝国和百姓沟通的媒介就是各村的邮差。村民平时遇到问题只需要交给邮差,国王就会迅速将处理 a结果交由邮差带回。 这天村民李二将一张名为”https://xxx.com/abc?name=li“ 的凭条交给了小张...

Error: Unexpected HTTP status 413 'Request Entity Too Large' on

由于nginx的client_max_body_size设置过小,默认上传的文件小于所要上传的文件大小,把这个值调大就可以了,我这里在配置文件的server下更改如下: server {     client_max_body_size 100M;     listen       80;     server_name  test.ssdd.twsapp...

Java 9 揭秘(19. 平台和JVM日志)

Tips做一个终身学习的人。 在这章中,主要介绍以下内容: 新的平台日志(logging)API JVM日志的命令行选项 JDK 9已经对平台类(JDK类)和JVM组件的日志系统进行了大整。 有一个新的API可以指定所选择的日志框架作为从平台类记录消息的日志后端。 还有一个新的命令行选项,可以从所有JVM组件访问消息。 在本章中,详细介绍两个记录工具...

centos lamp/lnmp阶段复习 以后搬迁discuz论坛不需要重新安装,只需修改配置文件即可 安装wordpress 安装phpmyadmin 定时备份mysql两种方法 第二十五节课

centos  lamp/lnmp阶段复习 以后搬迁discuz论坛不需要重新安装,只需修改配置文件即可 安装wordpress  安装phpmyadmin  定时备份mysql两种方法  第二十五节课 wordpress下载地址:https://cn.wordpress.org/ 架构:nginx代理 +LAMP 修改Windows的hosts文件 ap...

docker挂载单文件问题

关于docker中文件夹挂载成功 但是单文件挂载却没有生效的问题 因为用vim修改这里会有一个坑 docker -v mount 的机制:-v mount 文件(或文件夹)时,docker 记录的是该文件的 inode,并用 inode 追踪。当用 vim 编辑了文件后,这个文件的 inode 就变了,也就是说这个 default.conf 文件已经不是运...