Home  >  Article  >  Backend Development  >  PHP stores a large number of sessions in memory, hashing and expired recycling_PHP tutorial

PHP stores a large number of sessions in memory, hashing and expired recycling_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:38:561228browse

A server has relatively large traffic. Due to the needs of the program, the session expiration time is set to 3 hours, resulting in the accumulation of nearly 200,000 session files under /tmp. This in turn leads to a sharp increase in CPU usage by the kernel. Because session reading and writing involves random reading and writing of a large number of small files, and they are concentrated in one directory, iowait also increases sharply.

First consider putting the session into memory. The easiest way is to mount /tmp as a tmpfs file system, which is in memory
For details, see Using memory as a temporary folder under Linux

The second step is to store the session in a different directory
PHP itself supports multi-level hashing of sessions
In php.ini, change ;session.save_path = /tmp to

session.save_path = "2;/tmp/session"

means to store the session in the folder /tmp/session, and use 2 and hash.
Save and exit, wait until the third step is completed and restart php

The third step is to create the session storage folder
PHP does not automatically create these folders, but some scripts for creating folders are provided in the source file. The following script is also useful

I="0 1 2 3 4 5 6 7 8 9 a b c d e f"
for acm in $I;
do
for x in $I;
do
mkdir -p /tmp/session/$acm/$x;
done;
done
chown -R nobody:nobody /tmp/session
chmod -R 1777 /tmp/session

Because /tmp is used for memory, all files in it will be lost after the server is restarted. Therefore, the above script needs to be added to /etc/rc.local and placed before starting php

The fourth step, session recycling
The session will expire after session.gc_maxlifetime, but it will not be deleted immediately. After a long time, the /tmp space will be occupied. I'm too lazy to study the specific deletion algorithm. The following command can delete expired sessions. The expiration time I define here is 3 hours

find /tmp/session -amin +180 -exec rm -rf {} ;

Put it into cron, execute it every 10 minutes, and it’s done.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486449.htmlTechArticleA server has relatively large traffic. Due to the needs of the program, the session expiration time is set to 3 hours, resulting in/ Nearly 200,000 session files are accumulated under tmp. In turn, the CPU occupied by the kernel is urgent...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn