nginx可以作為Web前置機,将客戶請求按照一定算法合理配置設定給後置的tomcat應用伺服器,進而達到均衡目的。當然如果應用使用了session會話,後
置的tomcat應用還要保證session共享才能達到應用叢集效果。本文不讨論tomcat的叢集問題,重點讨論nginx如何配置使後置的tomcat負載均衡使用者
請求。
nginx.conf中,http { 下加入如下upstream塊,指明後置的兩台tomcat:
upstream tomcat {
server localhost:8280 weight=1 max_fails=1 fail_timeout=30s;
server localhost:8180 weight=4 max_fails=2 fail_timeout=30s;
}
同時定義server塊中的proxy_pass,指向上面定義的upstream:
server {
listen 8888;
server_name api.my.com;
access_log logs/api.zfwx.com main;
location / {
root html;
index index.html index.htm;
proxy_connect_timeout 3;
proxy_send_timeout 30;
proxy_read_timeout 30;
proxy_pass http://tomcat;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
此時,用戶端通路http://api.my.com:8888 請求會分别轉向後置的兩個tomcat。