zoukankan      html  css  js  c++  java
  • 防止短连接耗尽你的动态TCP端口

    摘要: 用pgbench使用短连接压测一个PostgreSQL数据库(select 1),其他数据库亦如此。 $ vi test.sql select 1; $ export PGPASSWORD=digoal $ pgbench -M simple -C -n -r -P 1 -c 800

    用pgbench使用短连接压测一个PostgreSQL数据库(select 1),其他数据库亦如此。

    $ vi test.sql
    select 1;
    
    $ export PGPASSWORD=digoal
    $ pgbench -M simple -C -n -r -P 1 -c 800 -j 80 -T 1000 -h xxx.xxx.xxx.xxx -p xxxx -U xxx dbname

    压测一段时间之后,可能会因为本地(客户端)的端口耗尽,客户端会报错如下

    connection to database "postgres" failed:
    could not connect to server: Cannot assign requested address
            Is the server running on host "xxx.xxx.xxx.xxx" and accepting
            TCP/IP connections on port 1925?
    connection to database "postgres" failed:
    could not connect to server: Cannot assign requested address
            Is the server running on host "xxx.xxx.xxx.xxx" and accepting
            TCP/IP connections on port 1925?

    原因是客户端需要为每一个连接动态创建TCP端口,所以每个连接会消耗一个端口。 
    客户端主动断开连接后,会进入TIME_WAIT状态。 


    详见TCP协议 
    https://en.wikipedia.org/wiki/Transmission_Control_Protocol
    Tcp_state_diagram_fixed_new_svg
    但是TIME_WAIT是有时间窗口的,Linux默认是60秒。 
    所以如果不停的产生和关闭TCP会话,就可能导致前面提到的问题。 


    对于Linux的客户端,通过调整几个操作系统内核参数可以解决这个问题。

    net.ipv4.tcp_syncookies=1   # 开启SYN Cookies。当出现SYN等待队列溢出时,启用cookie来处理,可防范少量的SYN攻击
    net.ipv4.tcp_tw_recycle=1   # 开启TCP连接中TIME-WAIT套接字的快速回收
    net.ipv4.tcp_tw_reuse=1     # 开启重用。允许将TIME-WAIT套接字重新用于新的TCP连接
    net.ipv4.tcp_timestamps=1   # 减少time_wait
    net.ipv4.tcp_tw_timeout=3   # 收缩TIME_WAIT状态socket的回收时间窗口
    https://yq.aliyun.com/articles/52884?spm=a2c4g.11186623.2.2.ZwsD5B
  • 相关阅读:
    javascript 面向对象 new 关键字 原型链 构造函数
    前端性能优化之gzip
    电子商务秒杀所带来的问题
    git 远程版本库,github提供服务原理,git自动更新发送邮件
    单点登陆的三种实现方式(详解)
    使用php实现单点登录
    支付宝异步回调
    http状态码大全
    php 单向散列加密
    curl模拟post请求
  • 原文地址:https://www.cnblogs.com/diyunpeng/p/9233002.html
Copyright © 2011-2022 走看看