解决nginx+php/java/go/python+mysql下time_wait连接数过多问题[转]
<p>公司服务器连接数超过10K了,查了下大多数是没有即时回收,采用tcp复用容易后程序出现了故障,以前一直看到说PHP持久连接有问题,所以没怎么用,最近有机会试了下。</p><p>非常香,连接数直接降低到几百了,目前观察数周没有问题。</p>
<h2>查看连接数</h2>
<pre>
netstat -n |wc -l # 总连接数
netstat -n | grep -i time_wait | wc -l # time_wait 连接数
netstat -anp # 查看占用端口过多的程序</pre>
<h2>tcp复用解决方案</h2>
<p>网上大部分解决方案是修改sysctl.conf回收重用ipv4连接,但是可能带来其他问题</p>
<pre>
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_timestamps=1
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_keepalive_time = 600</pre>
<h2>nginx fastcgi(php) 解决方案</h2>
<p>修改nginx.conf</p>
<pre>
upstream fastcgi_backend {
server 127.0.0.1:9000;
keepalive 60;
}
location ~ \.php$ {
fastcgi_passfastcgi_backend;
fastcgi_keep_conn on;
fastcgi_indexindex.php;
fastcgi_paramSCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
</pre>
<p>主要是 fastcgi_keep_conn on 与 upstream 的 keepalive</p>
<h2>nginx + proxy (python/go/java) 解决方案</h2>
<pre>
upstream wxpic {
keepalive 60;
server 127.0.0.1:xxx;
}
server {
keepalive_requests 10000; # 默认100
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}</pre>
<p>主要是 proxy_http_version, proxy_set_header Connection ""以及keepalive_requests</p>
<h2>mysql数据库连接解决方案</h2>
<p>修改yii数据库配置采用长链接</p>
<pre>
'db' => [
'class' => 'yii\db\Connection',
'dsn' => '*', 'username' => '*',
'password' => '*',
'charset' => 'utf8mb4',
'attributes' => [
PDO::ATTR_PERSISTENT => true
]
],
</pre>
<h2>redis 连接数</h2>
<h2>Yii redis 持久配置</h2>
<pre>
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => '127.0.0.1',
'retries' => 3,
'port' => 6379,
'password' => '',
'socketClientFlags' => STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT,
],</pre>
<h2>predis redis 持久配置</h2>
<pre>
$client = new \Predis\Client([
'scheme' => 'tcp',
'host' => $redis->hostname,
'port' => $redis->port,
'password' => $redis->password,
'persistent'=>true,
]);</pre>
<h2>phpredis redis 持久配置</h2>
<pre>
$redis->pconnect('127.0.0.1', 6379);</pre>
<p> </p>
<p>源文地址:https://c4ys.com/archives/1609</p>
页:
[1]