Nginx+Tomcat+Redis實現負載均衡、資源分離、session共享
CentOS安裝Nginx
http://centoscn.com/CentosServer/www/2013/0910/1593.html
CentOS安裝Tomcat
http://blog.csdn.net/zhuying_linux/article/details/6583096
CentOS安裝Redis
http://www.cnblogs.com/zhuhongbao/archive/2013/06/04/3117997.html
nginx官網:https://www.nginx.com/resources/wiki/modules/redis2/
多個Tomcat負載均衡例項:可在伺服器上覆製出多個Tomcat分別修改Tomcat的
http訪問埠(預設為8080埠)
Shutdown埠(預設為8005埠)
JVM啟動埠(預設為8009埠)
1、Nginx實現多Tomcat負載均衡
Tomcat服務
192.168.1.177:8001
192.168.1.177:8002
192.168.1.177:8003
Nginx配置
upstream mytomcats {
server 192.168.1.177:8001;
server 192.168.1.177:8002;
server 192.168.1.177:8003;
}
server {
listen 80;
server_name www.iu14.com;
location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
root /web/www/html/;
}
location / {
proxy_pass http://mytomcats;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
}
upstream指定負載均衡組,指定其Tomcat成員
location ~* \.(jpg|gif|……實現了靜態資源分離。ps:在location指令使用正規表示式後再用alias指令,Nginx是不支援的。
2、Nginx實現靜態資源分離
Tomcat服務
192.168.1.177:8000
Nginx配置
server {
listen 80;
server_name www.iu14.com;
root /web/www/html;
location /img/ {
alias /web/www/html/img/;
}
location ~ (\.jsp)|(\.do)$ {
proxy_pass http://192.168.1.177:8000;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
}
第一個location指令將/web/www/html/img/目錄下的靜態檔案交給Nginx來完成。最後一個location指令將所有以.jsp、.do結尾的檔案都交給Tomcat伺服器的8080埠來處理。
3、Nginx+Tomcat+Redis實現session共享
Redis服務
192.168.1.178:6379
Tomcat服務
192.168.1.177:8001
192.168.1.177:8002
192.168.1.177:8003
Nginx服務
192.168.1.179
配置Tomcat讓其session儲存到redis上,在context.xml配置(Value標籤一定要在Manager標籤前面):
配置Nginx
upstream mytomcats {
server 192.168.1.177:8001;
server 192.168.1.177:8002;
server 192.168.1.177:8003;
}
log_format www_iu14_com '$remote_addr - $remote_user [$time_local] $request ' '"$status" $body_bytes_sent "$http_referer"' '"$http_user_agent" "$http_x_forwarded_for"';
server {
listen 80;
server_name www.iu14.com;
location / {
proxy_pass http:// mytomcats;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
access_log /usr/tmp/logs/redis.iu14.log www_iu14_com;
}
依次啟動Redis、Tomcat、Nginx,訪問Nginx