利用nginx+tomcat配置负载均衡,配了两台tomcat,直接访问tomcat速度是很快的,但是配置完后访问速度变得很慢,然后查看了nginx的错误日志:
upstream timed out (10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) while connecting to upstream, client: 183.128.230.122, server: www.xxx.com, request: “POST /ytx/web/check/tasklistJson HTTP/1.1”, upstream: “http://120.27.203.130:8083/ytx/web/check/tasklistJson”, host: “www.xxx.com”, referrer: “http://www.xxx.com/ytx/web/home/checkTask”
解决办法:在upstream里加上ip_hash,然后访问就正常了。
upstream group1{
ip_hash;
server localhost:8080 ;
server localhost:8081 ;
}
原理分析:
ip_hash是根据ip分配吧,默认是轮询的,看你的情况应该是有一台主机挂了,然后刚好轮询到这台主机,所以需要等它响应超时才分配到另一台主机,而改成ip_hash的话应该是你本地ip刚好分配到好的那台主机,但其他ip则有可能访问到挂了的那台,到时候同样会出现长时间等待的情况。你这里应该设置proxy_connect_timeout的值,把连接超时设置的低一点,到时候访问主机响应时间超过设定时间后,就会访问另外的主机。