nginx+tomcat开启负载缓存配置记录
1、说明当前情况是nginx做前段负载均衡服务器,后端用4台tomcat提供web服务,现在要增加nginx的cache缓存服务器功能
nginx+keepalived: 192.168.0.1、192.168.0.2
tomcat1:192.168.0.1
tomcat2:192.168.0.2
tomcat3:192.168.0.5
tomcat4:192.168.0.7
2、添加nginx模块
purge模块下载地址:https://labs.frickle.com/nginx_ngx_cache_purge/
wget https://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
tar xf ngx_cache_purge-2.3.tar.gz -C /opt/
./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --add-module=/opt/ngx_cache_purge-2.3
make && make install
注:在进行编译前,要查看之前编译安装,用了哪些参数,要一起加上
# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.8.0
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-16) (GCC)
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
3、修改nginx配置文件
在http区域,添加如下
http {
..........................................
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
proxy_connect_timeout 60;
proxy_read_timeout 60;
proxy_send_timeout 60;
proxy_temp_path /data/proxy_nginx/temp;
proxy_cache_path /data/proxy_nginx/cache levels=1:2 keys_zone=cache_ahwap:500m inactive=1d max_size=30g;
#注:proxy_temp_path和proxy_cache_path指定的路径必须在同一分区
#设置Web缓存区名称为cache_ahwap,内存缓存空间大小为500MB,7天没有被访问的内容自动清除,硬盘缓存空间大小为30GB
..............................................
}
location区域添加如下:
location ~*(/..../..../...) {
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_ahwap;
proxy_cache_valid 200 304 12h;
proxy_cache_key $host$uri$is_args$args;
}
location ~ /purge(/.*)
{
allow 127.0.0.1;
allow 192.168.0.188;
deny all;
proxy_cache_purge cache_ahwap $host$1$is_args$args;
}
#用于清除缓存,假设一个URL为https://192.168.0.2/test.txt,通过访问https://192.168.0.2/purge/test.txt就可以清除该URL的缓存
#allow 192.168.0.188; 设置只允许指定的IP或IP段才可以清除URL缓存
location ~ .*\.(php|jsp|cgi|jhtml)?$ {
proxy_pass https://ahwap_services;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_cache cache_ahwap;
proxy_cache_valid 200 304 12h;
proxy_cache_key $host$uri$is_args$args;
}
#以上是设置扩展名以.php、.jsp、.cgi、jhtml结尾的动态应用程序不缓存。
4、重新加载nginx配置
加载前,先检查下配置可有误
# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
重新加载配置
# /usr/local/nginx/sbin/nginx -s reload
通过访问网站下某静态图片,即可看到效果。
到此配置完成nginx+tomcat开启负载缓存配置记录
评论