找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 79|回复: 0

[L/WNAMP] 解决nginx+php/java/go/python+mysql下time_wait连接数过多问题[转]

[复制链接]
发表于 2024-3-13 09:58 | 显示全部楼层 |阅读模式

公司服务器连接数超过10K了,查了下大多数是没有即时回收,采用tcp复用容易后程序出现了故障,以前一直看到说PHP持久连接有问题,所以没怎么用,最近有机会试了下。

非常香,连接数直接降低到几百了,目前观察数周没有问题。

查看连接数

netstat -n |  wc -l # 总连接数
netstat -n | grep -i time_wait | wc -l # time_wait 连接数
netstat -anp # 查看占用端口过多的程序

tcp复用解决方案

网上大部分解决方案是修改sysctl.conf回收重用ipv4连接,但是可能带来其他问题

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

nginx fastcgi(php) 解决方案

修改nginx.conf

upstream fastcgi_backend {
    server 127.0.0.1:9000;
    keepalive 60;
}

location ~ \.php$ {
        fastcgi_pass  fastcgi_backend;
        fastcgi_keep_conn on;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
}

主要是 fastcgi_keep_conn on 与 upstream 的 keepalive

nginx + proxy (python/go/java) 解决方案

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 "";
    }
}

主要是 proxy_http_version, proxy_set_header Connection ""以及keepalive_requests

mysql数据库连接解决方案

修改yii数据库配置采用长链接

'db' => [ 
    'class' => 'yii\db\Connection',
    'dsn' => '*', 'username' => '*', 
    'password' => '*', 
    'charset' => 'utf8mb4', 
    'attributes' => [ 
       PDO::ATTR_PERSISTENT => true 
    ]
],

redis 连接数

Yii redis 持久配置

   'redis' => [
        'class' => 'yii\redis\Connection',
         'hostname' => '127.0.0.1',
         'retries' => 3,
         'port' => 6379,
         'password' => '',
         'socketClientFlags' => STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT,
     ],

predis redis 持久配置

  $client = new \Predis\Client([
       'scheme' => 'tcp',
       'host' => $redis->hostname,
       'port' => $redis->port,
       'password' => $redis->password,
       'persistent'=>true,
  ]);

phpredis redis 持久配置

$redis->pconnect('127.0.0.1', 6379);

 

源文地址:https://c4ys.com/archives/1609

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|学习笔记

GMT+8, 2024-5-3 16:22 , Processed in 0.028180 second(s), 13 queries , APCu On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表