Home  >  Article  >  Backend Development  >  Detailed explanation of using memcache to store sessions based on PHP_PHP tutorial

Detailed explanation of using memcache to store sessions based on PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:03:29723browse

The php session of the web server is memcached, so you will have no problem no matter which web server the distributor assigns the IP connection to. The configuration method is very simple, just add a statement in the php configuration file
That’s it, but you need to install the memcache module

1. Set session to use memcache to store
Method I: Set globally in php.ini
session.save_handler = memcache
session.save_path = "tcp:// 127.0.0.1:11211"
Method II: .htaccess in a certain directory:
php_value session.save_handler "memcache"
php_value session.save_path "tcp://127.0.0.1:11211"
Method III: Or in a certain application:
ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://127.0.0.1:11211 ");
When using multiple memcached servers, separate them with commas ",", and as explained in the Memcache::addServer() document, you can take additional parameters "persistent", "weight", and "timeout" , "retry_interval" and so on, similar to this: "tcp://host1:port1?persistent=1&weight=2,tcp://host2:port2".
If the installed PECL is memcached (the one using the libmemcache library), the configuration should be
ini_set("session.save_handler", "memcached"); // It is memcached, not memcache
ini_set("session .save_path", "127.0.0.1:11211"); // Don't use tcp:

2. Start memcached:
memcached -d -l 127.0.0.1 -p 11212 -m 128
or start the server side of Memcache:
memcached -d -m 100 -u root -l 192.168.36.200 -p 11211 -c 256 -P /tmp/memcached.pid
# /usr/local/bin/memcached -d -m 10 -u root -l 192.168.0.200 -p 12000 -c 256 -P /tmp/memcached.pid
Reference
The -d option is to start a daemon process,
-m is the amount of memory allocated to Memcache, in MB , here I am 100MB,
-u is the user running Memcache, I am root here,
-l is the IP address of the listening server, if there are multiple addresses, I specified the IP address of the server 192.168 here .36.200,
-p is the port to set up Memcache monitoring. I set 11211 here, preferably a port above 1024. We use 11211 here
-c option is the maximum number of concurrent connections running, the default is 1024, I set 256 here, set it according to the load of your server.
-P is to set the pid file to save Memcache. I save it in /tmp/memcached.pid,

3. Use memcache for session storage in the program
Test it with an example:

Copy the code The code is as follows :

session_start();
if (!isset($_SESSION['TEST'])) {
$_SESSION['TEST'] = time();
}

$_SESSION['TEST3'] = time();

print $_SESSION['TEST'];
print "

";
print $_SESSION['TEST3'];
print "

";
print session_id();
?>

4. Use sessionid to query in memcached:
Copy the code The code is as follows:

$memcache = memcache_connect('localhost', 11211);
var_dump($memcache->get('19216821213c65cedec65b0883238c278eeb573e077'));
$mem cache->set ('aaaa', 'hello everyone');
var_dump($memcache->get('aaaa'));
?>

You will see output like
string(37) "TEST|i:1177556731;TEST3|i:1177556881;"
, which proves that the session is working normally.
Using memcache to store sessions will be much faster in reading and writing than files, and it will be more convenient when multiple servers need to share sessions. Just configure these servers to use the same group of memcached servers, which reduces extra costs. workload. The disadvantage is that the session data is stored in memory, which lacks persistence, but it is not a big problem for the session data.
====================================
Generally, Session is in the form of a text file Stored on the server side. If Seesion is used, or the PHP file wants to call the Session variable, it must be started before calling the Session, using the session_start() function. You don’t need to set anything else, PHP automatically completes the creation of the Session file. The default Session storage path is the system temporary folder of the server.
But if you encounter a session with a large amount of data, the bottleneck of using file-based session access may be disk IO operations. Now Memcached is used to save session data directly through memory, and the efficiency can naturally be improved. Quite a few. The read and write speed will be much faster than files, and it will be more convenient when multiple servers need to share sessions. Just configure these servers to use the same group of memcached servers, reducing additional workload.

The disadvantage is that the session data is stored in memory. Once the machine goes down, the data will be lost. But it is not a serious problem for session data.
How to use memcached to store sessions? The following are the basic configuration steps:
1. Install memcached
There will be "files user sqlite" in the "Registered save handlers" in the phpinfo output.

2. Modify the configuration file,
a. Global settings in php.ini (*requires restarting the server)
session.save_handler = memcache
session.save_path = "tcp ://127.0.0.1:11211"
b. Or .htaccess in a directory:
php_value session.save_handler "memcache"
php_value session.save_path "tcp:/ /127.0.0.1:11211"
c. It can also be used in an application:
ini_set("session.save_handler", "memcache");
ini_set("session .save_path", "tcp://127.0.0.1:11211");
Note: When using multiple memcached servers, use commas "," to separate them and Memcache:: As explained in the addServer() documentation, you can take additional parameters "persistent", "weight", "timeout", "retry_interval", etc., similar to this: "tcp://host:port?persistent=1&weight=2 ,tcp://host2:port2″.

3. Start memcached
memcached -d -m 10 -u root -l 127.0.0.1 -p 11211 -c 256 -P /tmp/memcached.pid

4. Test to create a session

Copy the code The code is as follows:

//set_session.php
session_start();
if (!isset($_SESSION['admin'])) {
$_SESSION['TEST'] = 'wan';
}
print $_SESSION['admin'];
print "n";
print session_id();
?>

5 . Use sessionid to query in memcached
Copy the code The code is as follows:

//get_session.php
$mem = new Memcache;
$mem->connect("127.0.0.1", 11211);
var_dump($mem->get('0935216dbc0d721d629f89efb89affa 6') );
?>

Copy code The code is as follows:

[root@localhost html]# /usr/local/webserver/php/bin/php -f get_session.php

Output result:
string(16)
"admin|s:3:"wan";"
Proves that session is working properly.
============================
Using memcache to store sessions should be faster in reading and writing than files It is much faster, and it is more convenient when multiple servers need to share sessions. Just configure these servers to use the same group of memcached servers, which reduces additional workload. The disadvantage is that session data is stored in memory and cannot be stored persistently. If you want to store it persistently, you can consider using Memcachedb for storage, or Tokyo Tyrant+Tokyo Cabinet for storage.

How to determine if the session has expired? There is a Session.cookie_lifetime option in php.ini. This represents the time that the SessionID is stored in the client cookie. The default value is "0", which means that the SessionID will be invalidated as soon as the browser is closed, regardless of whether the Session saved in Memcached is It is still valid (the session saved in Memcached will be processed using Memcached's internal mechanism, even if the session data has not expired, and since the client's SessionID has expired, this key will basically not have a chance to be used, using Memcached's LRU principle, If the memory of Memcached is not enough, new data will replace the expired and oldest unused data), because the SessionID has expired, a new SessionID will be regenerated on the client.

The longest data stored in Memcached will not exceed 30 days. This time is based on the time of operating Memcached. That is to say, as long as the key is still the original key, if you re-enter the key If related operations (such as set operations) are performed and the validity period is reset, the validity period of the data corresponding to this key will be recalculated at this time. The PHP manual explains

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

The main cache mechanism of Memcached is the LRU (least recently used) algorithm + timeout failure. When you store data in memcached, you can specify how long the data can stay in the cache. If memcached's memory is insufficient, expired slabs will be replaced first, followed by the oldest unused slabs.
============================
In order for web applications to use large-scale access in saas mode, the application must be implemented Cluster deployment. To achieve cluster deployment, it is mainly necessary to implement a session sharing mechanism to unify sessions between multiple application servers. Most services such as tomcat use session replication technology to achieve session sharing.
Problems with session replication technology :
(1) The technology is complex and must be completed between the same kind of middleware (such as: between tomcat-tomcat).
(2) As the number of nodes continues to increase, session replication will bring The performance loss will increase rapidly. Especially when larger objects are stored in the session and the objects change quickly, the performance drop will be more significant. This characteristic limits the horizontal expansion of web applications.

Another idea for session sharing is to centralize session management. The first thing that comes to mind is to use a database to centrally store sessions. However, file storage in a database is an order of magnitude slower than memory. At the same time, this will inevitably increase the burden on the database system. Therefore, a database is needed. A service that is both fast and can provide remote centralized storage, so I thought of memcached.

What can memcached cache?
By maintaining a unified huge hash table in memory, Memcached can be used to store data in various formats, including images, videos, files, and database retrieval results.

Is memcached fast?
Very fast. Memcached uses libevent (or epoll under Linux if you can) to balance any number of open connections, uses non-blocking network I/O, and implements reference counting for internal objects (so that objects can be processed for a variety of clients). In various states), uses its own page block allocator and hash table, so the virtual memory will not be fragmented and the time complexity of virtual memory allocation can be guaranteed to be O(1).
Pay attention to several issues and improvement ideas during use:
1. The memory of memcache should be large enough so that there will be no problem of user sessions being cleared from the cache (memcached objects can be closed exit mechanism).
2. If the session reads much more than writes, you can add a local cache such as Oscache in front of memcache to reduce the read operations on memcache, thereby reducing network overhead and improving performance.
3. If there are many users, you can use the memcached group, insert the hashCode into a memcached server through the set method
There are several options for clearing the session:
(1) You can clear memcached in the early morning when there are least people. (Simple)
(2) Set an expiration time for the objects stored in the cache, obtain the value of sessionId through the filter, and refresh the objects in memcached regularly. Objects that have not been refreshed for a long time are automatically cleared. (Relatively complicated, Consume resources)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327847.htmlTechArticleThe php session of the web server is memcached, so you don’t matter which web server the distributor assigns the IP connection to. There will be problems. The configuration method is very simple, just in the php configuration file...
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