杰克工作室 发表于 2024-3-13 09:58

解决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>主要是&nbsp;fastcgi_keep_conn on&nbsp;与&nbsp;upstream&nbsp;的&nbsp;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 &quot;&quot;;
    }
}</pre>

<p>主要是&nbsp;proxy_http_version,&nbsp;proxy_set_header Connection &quot;&quot;以及keepalive_requests</p>

<h2>mysql数据库连接解决方案</h2>

<p>修改yii数据库配置采用长链接</p>

<pre>
&#39;db&#39; =&gt; [
    &#39;class&#39; =&gt; &#39;yii\db\Connection&#39;,
    &#39;dsn&#39; =&gt; &#39;*&#39;, &#39;username&#39; =&gt; &#39;*&#39;,
    &#39;password&#39; =&gt; &#39;*&#39;,
    &#39;charset&#39; =&gt; &#39;utf8mb4&#39;,
    &#39;attributes&#39; =&gt; [
       PDO::ATTR_PERSISTENT =&gt; true
    ]
],
</pre>

<h2>redis 连接数</h2>

<h2>Yii redis 持久配置</h2>

<pre>
   &#39;redis&#39; =&gt; [
      &#39;class&#39; =&gt; &#39;yii\redis\Connection&#39;,
         &#39;hostname&#39; =&gt; &#39;127.0.0.1&#39;,
         &#39;retries&#39; =&gt; 3,
         &#39;port&#39; =&gt; 6379,
         &#39;password&#39; =&gt; &#39;&#39;,
         &#39;socketClientFlags&#39; =&gt; STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT,
   ],</pre>

<h2>predis redis 持久配置</h2>

<pre>
$client = new \Predis\Client([
       &#39;scheme&#39; =&gt; &#39;tcp&#39;,
       &#39;host&#39; =&gt; $redis-&gt;hostname,
       &#39;port&#39; =&gt; $redis-&gt;port,
       &#39;password&#39; =&gt; $redis-&gt;password,
       &#39;persistent&#39;=&gt;true,
]);</pre>

<h2>phpredis redis 持久配置</h2>

<pre>
$redis-&gt;pconnect(&#39;127.0.0.1&#39;, 6379);</pre>

<p>&nbsp;</p>

<p>源文地址:https://c4ys.com/archives/1609</p>
页: [1]
查看完整版本: 解决nginx+php/java/go/python+mysql下time_wait连接数过多问题[转]