當(dāng)進(jìn)行大并發(fā)的壓力測試時(shí),經(jīng)常會(huì)出現(xiàn)如下Exception:Too many open files.
查閱資料,google baidu.
首先感謝demo的評論,使我對這個(gè)問題有了新的認(rèn)識。
經(jīng)過再次查找,發(fā)現(xiàn)這個(gè)問題的出現(xiàn)原因是system對打開files數(shù)量的限制問題。
用 ulimit -a 命令可以查看當(dāng)前所有資源限制
fingki@ubuntu:~$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 15863
max locked memory (kbytes, -l) 32
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 15863
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
fingki@ubuntu:~$
可以看出,對open files的限制數(shù)是1024,我們可以通過修改這個(gè)值來增加可以打開的文件數(shù)。
最簡單的修改方式就是用ulimit -n 命令,
比如我打算將其改為2048,用 ulimit -n 2048.
當(dāng)你把open files的值增大到一定程度,你的Too many open files就不會(huì)再出現(xiàn)了。
而對于tcp_fin_timeout,是合tcp連接相關(guān)的,當(dāng)你有大量tcp連接時(shí),或許有些性能改善;
tcp_fin_timeout,默認(rèn)情況下,win為4 min,linux為60 sec.
可以把其相應(yīng)設(shè)置短一些,以增加系統(tǒng)性能。
in Windows
- Run regedit to start the Registry Editor
- Locate the following key: HKEY_LOCAL_MACHINE"System"CurrentControlSet"Services"tcpip"Parameters
- Add a new value named TcpTimedWaitDelay asa decimal and set the desired timeout in seconds (30-300)
- Reboot
in Linux
- Update the configuration value by running (30 seconds used in the example)
echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout
- Restart the networking component, for example by running
/etc/init.d/networking restart or service network restart
在linux下,經(jīng)常會(huì)有權(quán)限問題使設(shè)置不能成功,盡管你用了sudo。
解決辦法就是先 su root,在root用戶下來執(zhí)行操作,這樣就ok了。
再有就是可能忘記root密碼了,那就 sudo passwd root,來設(shè)置一個(gè)新密碼。
根據(jù)進(jìn)一步的研究發(fā)現(xiàn):服務(wù)器默認(rèn)情況下對進(jìn)程的處理也是有限制的,要想server處理更多用戶進(jìn)程就需要調(diào)整相應(yīng)參數(shù)。
這里面有兩個(gè)文件要特別注意,
一個(gè)是 /etc/security/limits.conf
另一個(gè) /etc/sysctl.conf
當(dāng)我們用ulimit -a命令可以查看 open files(默認(rèn)為1024)和max user processes(默認(rèn)也為1024),
所以默認(rèn)情況下這個(gè)server只允許同時(shí)打開1024個(gè)文件,處理1024個(gè)用戶進(jìn)程,
若要 臨時(shí) 改變這兩個(gè)參數(shù)值,可以使用 ulimit -n 10240 ,ulimit -u 10240,
若要 長久 改變這兩個(gè)參數(shù)值,就要修改/ect/security/limits.conf,在文件中加上兩行:
* - nofile 102400
* - nproc 102400
而對于大量使用tcp連接的應(yīng)用來說,也需要對/etc/sysctl.conf中的參數(shù)進(jìn)行相應(yīng)優(yōu)化:
net/ipv4/ip_always_defrag = 1
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_max_syn_backlog = 102400
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
上面是我根據(jù)我的需求的一些參數(shù)調(diào)整,你可以根據(jù)你的需求來調(diào)整相應(yīng)參數(shù)值。
然后執(zhí)行
sysctl -p命令可立即生效。sysctl -a可查看參數(shù)值。
參考 :http://www.javaeye.com/topic/65175