一、通常情况下,一台Tomcat站点由于可能出现单点故障及无法应付过多客户复杂多样的请求等问题。不能单独应用于生产环境下。所以我们需要一套更可靠的解决方案来完善web站点架构。目前很多大型企业都应用nginx服务器作为后端网站程序的方向代理及负载均衡器。来提升整个站点的负载并发能力。
二、上一篇给大家介绍了如何安装Tomcat。在本篇不在过多叙述!(Tomcat2和上一篇安装步骤一样。只需把index.jsp的测试文件内容修改一下即可)
三、nginx服务器安装及配置
yum -y install pcre-devel zlib-devel openssl-devel //nginx相关软件包
groupadd nginxgroup
useradd -g nginxgroup -s /bin/false nginx
tar zxf nginx-1.6.....gz
cd nginx-1.6.0
./configure --prefix=/usr/local/nginx --user=nginx --group=nginxgroup --with-file-aio --with-http_stub_status_module --with-http_gzip_static_module --with-http_flv_module --with-http_ssl_module && make && make install
注: --with-file-aio //启动文件修改支持
--with-http_stub_status_module //启用状态统计
--with-http_gzip_static_module //启用gzip静态压缩
--with-http——flv——module //启用flv模块,提供寻求内存使用基于时间的偏移量文件
--with-http——ssl——module //启用ssl模块
2)vim /usr/local/nginx/conf/nginx.conf
1.// 在http{....}中加入以下代码。设置负载均衡的服务器列表。weight参数表示权值。权值越高被分配到的概率越大。
upstream tomcat_server {
server 192.168.10.100:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.10.101:8080 weight=1 max_fails=2 fail_timeout=30s;
}
2.// 在http{......}-server{......} - location / {....}中加入一行
proxy_pass http://tomcat_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
location = / {
#判断是否为手机移动端
if ($http_user_agent ~* '(iPhone|ipod|iPad|Android|Windows Phone|Mobile|Nokia)') {
rewrite . http://www.nginxtest.net/phone break;
}
rewrite . http://www.nginxtest.net/pc break;
}
}
以上配置是为了将默认站点通过proxy_pass方法代理到设定好的TOMCAT_SERVER负载均衡服务器组上。
4)如果要做动静分离,只需要在nginx添加如下配置就OK了。
#配置Nginx动静分离
location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
{
root /data/www;
#expires定义用户浏览器缓存的时间为3天,如果静态页面不常更新,可以设置更长,这样可以节省带宽和缓解服务器的压力
expires 3d;
}
3)检测
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ps aux | grep nginx
netstat -antpu |grep nginx
4)访问即可