同時実行性が高い場合に Web サーバーとキャッシュ サーバーのソケット接続制限の最大数を調整する方法

PHPz
リリース: 2024-07-18 18:44:23
オリジナル
185 人が閲覧しました

高并发下 web 服务器和 cache 服务器 socket 最大连接数限制调整方法

web服务器和cache服务器,高并发下,socket最大联接数限制调整:

1,更改用户进程可打开最大文件数限制。

即时生效:ulimit-nxxx

永久生效:

echo"ulimit-HSn65536">>/etc/rc.local

echo"ulimit-HSn65536">>/root/.bash_profile

ulimit-HSn65536

2,更改网路内核对最大tcp联接数限制。

/etc/sysctl.conf

一、

在Linux平台上,无论编撰顾客端程序还是服务端程序,在进列宽并发TCP联接处理时,最高的并发数目都要遭到系统对用户单一进程同时可打开文件数目的限制(这是由于系统为每位TCP联接都要创建一个socket句柄,每位socket句柄同时也是一个文件句柄)。诸如:一个redis程序,只启动一个进程,则只能打开1024个文件(默认1024)(1024个tcp联接=1024个socket联接句柄=1024个文件句柄),

可使用ulimit命令查看系统容许当前用户进程打开的文件数限制:

$ulimit-n

1024

这表示当前用户的每位进程最多容许同时打开1024个文件,这1024个文件中还得去除每位进程必然打开的标准输入,标准输出,标准错误,服务器窃听socket,进程间通信的unix域socket等文件,这么剩下的可用于顾客端socket联接的文件数就只有大约1024-10=1014个左右。也就是说缺省情况下,基于Linux的通信程序最多容许同时1014个TCP并发联接。

对于想支持更高数目的TCP并发联接的通信处理程序,就必须更改Linux对当前用户的进程同时打开的文件数目:

软限制(softlimit):是指Linux在当前系统还能承受的范围内进一步限制用户同时打开的文件数;

硬限制(hardlimit):是依据系统硬件资源状况(主要是系统显存)估算下来的系统最多可同时打开的文件数目。

一般软限制大于或等于硬限制

更改单个进程打开最大文件数限制的最简单的办法就是使用ulimit命令:

[speng@as4~]$ulimit-n

上述命令中,在手指定要设置的单一进程容许打开的最大文件数。假如系统回显类似于"Operationnotpermitted"之类的话嵌入式linux培训,说明上述限制更改失败,实际上是由于在手指定的数值超过了Linux系统对该用户打开文件数的软限制或硬限制。因而,就须要更改Linux系统对用户的关于打开文件数的软限制和硬限制。

第一步,更改/etc/security/limits.conf文件,在文件中添加如下行:

spengsoftnofile10240

spenghardnofile10240

speng specifies the limit on the number of open files for that user to be changed. The '*' sign can be used to indicate changing the limit for all users;

soft or hard specifies whether to change the soft limit or the hard limit; 10240 specifies the new limit value you want to change, that is, the maximum number of open files (please note that the soft limit value must be greater than or equal to the hard limit). Save the file after making changes.

The second step is to change the /etc/pam.d/login file and add the following lines to the file:

sessionrequired/lib/security/pam_limits.so This tells Linux that after the user completes the system login, the pam_limits.so module should be called to set the system’s maximum limit on the number of various resources that the user can use (including the maximum number of resources that the user can open) file number limit), and the pam_limits.so module will read the configuration from the /etc/security/limits.conf file to set this limit value. Save this file after making changes.

The third step is to check the Linux system-level limit on the maximum number of open files, use the following command:

[speng@as4~]$cat/proc/sys/fs/file-max

12158

This shows that this Linux system can allow up to 12158 files to be opened at the same time (that is, including the total number of files opened by all users), which is a Linux system-level hard limit. All user-level limits on the number of open files should not exceed this value. Generally, this system-level hard limit is the best maximum limit on the number of files opened at the same time based on the system hardware resources when the Linux system is started. If there is no special need, this limit should not be changed unless you want to limit the number of files opened at the user level. Set a value that exceeds this limit.

The way to change this hard limit is to change the /etc/rc.local script and add the following line to the script:

linux tcp连接数限制_限制连接数的固件_限制连接数量

echo22158>/proc/sys/fs/file-max

This is to force Linux to set the system-level hard limit on the number of open files to 22158 after the startup is completed. Save this file after the change.

After completing the above steps, restart the system. Normally, you can set the maximum number of files that the Linux system allows a single process of a specified user to open at the same time to a specified value. If after restarting, you use the ulimit-n command to check that the limit on the number of files that a user can open is always higher than the maximum value set in the above steps, this may be because the ulimit-n command in the user login script /etc/profile has already disabled the number of files that the user can open at the same time. The number of files is limited. Because when you use ulimit-n to change the system's limit on the maximum number of files that a user can open at the same time, the new changed value can only be greater than or equal to the value previously set by ulimit-n. Therefore, it is impossible to use this command to reduce this limit value. .

So, if the above problem exists, you can only open the /etc/profile script file and search in the file to see if ulimit-n is used to limit the maximum number of files that the user can open at the same time. If found, delete this line command, or change the value set to an appropriate value, save the file, and then the user can exit and log in to the system again. Through the above steps, the system limit on the number of open files is lifted for the communication processing program that supports high-concurrency TCP connection processing.

2. Modify the network kernel’s restrictions on TCP connections

When writing a client communication handler on Linux that supports high-concurrency TCP connections, you sometimes find that although the system has lifted the limit on the number of files users can open at the same time, there will still be problems when the number of concurrent TCP connections drops to a certain number. It also fails to successfully establish a new TCP connection. There are many reasons for these occurrences.

첫 번째 이유는 Linux 네트워크 커널이 로컬 포트 ​​번호 범위에 제한이 있기 때문일 수 있습니다. 이때 TCP 연결을 완료할 수 없는 이유를 자세히 분석해 보면 connect() 호출이 반환되지 않는 것이 문제라는 것을 알 수 있습니다. 동시에, "요청한 주소를 할당할 수 없습니다." 이때 tcpdump 도구를 사용하여 네트워크를 모니터링하면 TCP 연결 중에 클라이언트가 SYN 패킷을 보낼 네트워크 트래픽이 없는 것으로 나타났습니다. 이 상황은 문제가 로컬 Linux 시스템 커널의 제한 사항에 있음을 나타냅니다.

문제의 근본 원인은 Linux 커널의 TCP/IP 계약 구현 모듈이 시스템의 모든 클라이언트 TCP 연결에 해당하는 로컬 포트 ​​번호 범위를 제한한다는 것입니다(예: 커널은 로컬 포트 ​​범위를 제한합니다) 숫자는 1024~32768 사이). 특정 시간에 시스템에 너무 많은 TCP 클라이언트 연결이 있는 경우, 각 TCP 클라이언트 연결이 고유한 로컬 포트 ​​번호를 차지하기 때문에(이 포트 번호는 시스템의 로컬 포트 ​​번호 범위 제한 내에 있음) 일부 TCP 클라이언트 연결에 모든 로컬 포트 ​​번호를 점유하고 있으며 새 TCP 클라이언트 연결을 위한 로컬 포트 ​​번호를 할당하기가 어렵습니다. 이러한 이유로 시스템은 이러한 경우에 connect() 호출을 반환하고 오류 메시지를 "Can"으로 설정합니다. '요청된 주소 할당'.

이 제어 로직의 경우 Linux 커널 소스 코드를 볼 수 있습니다. linux2.6 커널을 예로 들면 tcp_ipv4.c 파일에서 다음 기능을 볼 수 있습니다.

staticinttcp_v4_hash_connect(structsock*sk)

위 함수에서 sysctl_local_port_range 변수에 대한 액세스 제어를 참고하세요. sysctl_local_port_range 변수의 초기화는 tcp.c 파일의 다음 함수에서 설정됩니다.

void__inittcp_init(무효)

커널 컴파일 시 설정된 기본 로컬 포트 ​​번호 범위가 너무 작을 수 있으므로 이 로컬 포트 ​​범위 제한을 변경해야 합니다.

첫 번째 단계는 /etc/sysctl.conf 파일을 변경하여 Linux 시스템 이미지를 다운로드하고 파일에 다음 줄을 추가하는 것입니다.

net.ipv4.ip_local_port_range=102465000

이는 시스템의 로컬 포트 ​​범위 제한이 1024~65000 사이로 설정되어 있음을 나타냅니다. 로컬 포트 ​​범위의 최소값은 1024보다 작거나 같아야 하며 포트 범위의 최대값은 65535보다 크거나 같아야 합니다. 변경한 후 이 파일을 저장하십시오.

두 번째 단계는 sysctl 명령을 실행하는 것입니다:

限制连接数量_限制连接数的固件_linux tcp连接数限制

[speng@as4~]$sysctl-p

시스템에 오류 메시지가 없으면 새 로컬 포트 ​​범위가 성공적으로 설정되었음을 의미합니다. 위의 포트 범위에 따라 설정하면 이론적으로 단일 프로세스가 동시에 60,000개 이상의 TCP 클라이언트 연결을 완료할 수 있습니다.

TCP 연결 완료에 실패하는 두 번째 이유는 Linux 네트워크 커널의 방화벽에 추적되는 최대 TCP 연결 수에 제한이 있기 때문일 수 있습니다. 이때 프로그램은 종료된 것처럼 connect() 호출에서 차단된 것으로 나타납니다. tcpdump 도구를 사용하여 네트워크를 모니터링하면 클라이언트가 SYN을 보낼 네트워크 트래픽도 없는 것을 알 수 있습니다. TCP 연결 중 패킷. 방화벽은 커널의 각 TCP 연결 상태를 추적하므로 추적 정보는 커널 메모리에 있는 conntrack 데이터베이스에 저장됩니다. 시스템에 TCP 연결이 너무 많으면 이 데이터베이스의 크기가 제한됩니다. 데이터베이스 용량이 부족하여 IP_TABLE이 새 TCP 연결에 대한 추적 정보를 구축하지 못하여 connect() 호출이 차단된 것으로 나타났습니다. 이 시점에서 추적되는 최대 TCP 연결 수에 대한 커널 제한을 변경해야 합니다. 이 기술은 로컬 포트 ​​번호 범위에 대한 커널 제한을 변경하는 것과 유사합니다.

첫 번째 단계는 /etc/sysctl.conf 파일을 변경하고 파일에 다음 줄을 추가하는 것입니다.

net.ipv4.ip_conntrack_max=10240

これは、追跡される TCP 接続の最大数に対するシステムの制限が 10240 に設定されていることを示します。カーネル メモリの使用量を節約するには、この制限値をできるだけ小さくする必要があることに注意してください。

2 番目のステップは、sysctl コマンドを実行することです:

[speng@as4~]$sysctl-p

システムにエラー メッセージがない場合は、システムが追跡される TCP 接続の新しい最大数の制限を正常に変更したことを意味します。上記のパラメータが設定されている場合、理論的には、1 つのプロセスで 10,000 を超える TCP クライアント接続を同時に完了できます。

三、

高同時実行ネットワーク I/O をサポートするプログラミング テクノロジを使用して、Linux 上で高同時実行 TCP 接続アプリケーションをコンパイルする場合は、適切なネットワーク I/O テクノロジと I/O ストーム ディスパッチ メカニズムを使用する必要があります。利用可能な I/O テクノロジには、同期 I/O、ノンブロッキング同期 I/O (リアクティブ I/O とも呼ばれます)、および非同期 I/O が含まれます (同期 I/O が使用される場合、TCP 同時実行性が高くなります)。これにより、各 TCP 接続の I/O に対してスレッドが作成されない限り、プログラムの動作が大幅にブロックされます。

ただし、linux tcp 接続数制限 では、スレッドが多すぎると、システムのスレッド スケジューリングにより莫大な費用が発生します。このため、TCP 同時実行性が高い状況では同期 I/O を使用することはお勧めできません。この場合、ノンブロッキング同期 I/O または非ブロッキング同期 I/O 技術の使用を検討できます。 select ()、poll()、epoll およびその他のメカニズムを使用します。非同期 I/O の技術は AIO を使用することです。

I/O ストーム ディスパッチ メカニズムの観点から見ると、select() は限られた数の同時接続 (通常は 1024 以内) をサポートするため、これを使用するのは不適切です。パフォーマンスを考慮すると、poll() もlinux tcp 接続数制限 としては不適切ですが、より多くの TCP 同時実行をサポートでき、「コルーチン」メカニズムを使用しているため、同時実行数が多い場合には実行されます。効率は非常に低く、I/O ウェーブが不均一に分散され、一部の TCP 接続で I/O の「枯渇」が発生する可能性があります。 epoll または AIO を使用する場合、そのような問題はありません (Linux カーネルでの AIO テクノロジの初期実装は、カーネル内で各 I/O 要求ごとにスレッドを作成することによって実現されました。これらの実装メカニズムは、高負荷の場合に使用されます)。同時実行 TCP 接続にも重大なパフォーマンスの問題があるようです。しかし、最新の Linux カーネルでは、AIO の実装が長い間改善されてきました。

要約すると、高同時 TCP 接続をサポートする Linux アプリケーションを開発する場合は、epoll または AIO テクノロジを使用して同時 TCP 接続の I/O 制御を実現するようにしてください。これにより、高同時 TCP 接続を処理するプログラムの能力が向上します。サポートにより、効果的な I/O が保証されます。

カーネルパラメータsysctl.confの最適化

/etc/sysctl.conf は、Linux ネットワークを制御するために使用される構成ファイルであり、RHEL がデフォルトで最適な調整を提供する、ネットワークに依存するプログラムにとって非常に重要です。

推奨構成 (元の /etc/sysctl.conf の内容をクリアし、次の内容をそこにコピーします):

限制连接数量_限制连接数的固件_linux tcp连接数限制

cp/etc/sysctl.conf/etc/sysctl.conf.bak

echo"">/etc/sysctl.conf

vim/etc/sysctl.conf

net.ipv4.ip_local_port_range=102465535

net.core.rmem_max=16777216

net.core.wmem_max=16777216

net.ipv4.tcp_rmem=40968738016777216

net.ipv4.tcp_wmem=40966553616777216

net.ipv4.tcp_fin_timeout=10

net.ipv4.tcp_tw_recycle=1

net.ipv4.tcp_timestamps=0

net.ipv4.tcp_window_scaling=0

net.ipv4.tcp_sack=0

dev_max_backlog=30000

net.ipv4.tcp_no_metrics_save=1

net.core.somaxconn=10240

net.ipv4.tcp_syncookies=0

限制连接数量_linux tcp连接数限制_限制连接数的固件

net.ipv4.tcp_max_orphans=262144

net.ipv4.tcp_max_syn_backlog=262144

net.ipv4.tcp_synack_retries=2

net.ipv4.tcp_syn_retries=2

This configuration refers to the recommended configuration of cache server varnish and the recommended configuration of SunOne server system optimization.

However, the configuration recommended by Varnish is problematic. Actual operation shows that the configuration of "net.ipv4.tcp_fin_timeout=3" will often cause the page to fail to open; and when netizens use IE6 browsers, after visiting the website for a period of time, All web pages will be unable to be opened and will work normally after restarting the browser. It may be that the Internet speed in the United States is fast, but our national conditions determine that we need to adjust "net.ipv4.tcp_fin_timeout=10". In the case of 10 seconds, everything is normal (actual operation inference).

After the changes are completed, execute:

sysctl-p/etc/sysctl.conf

sysctl-wnet.ipv4.route.flush=1

The command takes effect. To be on the safe side, you can also reboot the system.

Adjust the maximum number of open file handles (maximum number of tcp connections in a single process = maximum number of socket connections in a single process):

After optimizing the network of the Linux system, the number of files allowed to be opened by the system must be increased to support large concurrency. The default 1024 is far from enough.

Execute command:

Shell code

echo "ulimit-HSn65536">>/etc/rc.local

echo "ulimit-HSn65536">>/root/.bash_profile

ulimit-HSn65535

以上が同時実行性が高い場合に Web サーバーとキャッシュ サーバーのソケット接続制限の最大数を調整する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:itcool.net
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!