Using Memcache to store session details based on PHP

Source: Internet
Author: User
Tags php session

The PHP session of the Web server is given to memcached, so you don't have a problem with which Web server the Distributor distributes IP connections to, and the configuration is simple, in the PHP configuration file
Add a statement on it, but if you need to install the Memcache module.

1. Set session with Memcache to store
Method I: Global settings in php.ini
Session.save_handler = Memcache
Session.save_path = "tcp://127.0.0.1:11211"
Method II:. htaccess in a directory:
Php_value Session.save_handler "Memcache"
Php_value Session.save_path "tcp://127.0.0.1:11211"
Method III: Again or in one application:
Ini_set ("Session.save_handler", "memcache");
Ini_set ("Session.save_path", "tcp://127.0.0.1:11211");
Use multiple memcached servers separated by commas "," and, as described in the memcache::addserver () documentation, can take additional parameters "persistent", "weight", "timeout", "Retry_ Interval "And so on, like 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's memcached, not memcache.
Ini_set ("Session.save_path", "127.0.0.1:11211"); Do not 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,
-M is the amount of memory allocated to Memcache, in megabytes, I'm 100MB,
-U is the user running memcache, I am root here,
-L is the server IP address of the listener, if there are multiple addresses, I specify the server IP address 192.168.36.200,
-P is set memcache listening port, I set up here 11211, preferably more than 1024 ports, we use this uniform 11211
The-c option is the maximum number of concurrent connections to run, the default is 1024, I set 256 here, according to the amount of load on your server to set.
-P is set to save memcache PID file, I am here to save in/tmp/memcached.pid,

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

The code is as follows:
<?php
Session_Start ();
if (!isset ($_session[' TEST ')) {
$_session[' TEST ' = time ();
}

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

Print $_session[' TEST '];
print "<br><br>";
Print $_session[' TEST3 '];
print "<br><br>";
Print session_id ();
?>


4. Check with SessionID to memcached:

The code is as follows:
<?php
$memcache = Memcache_connect (' localhost ', 11211);
Var_dump ($memcache->get (' 19216821213c65cedec65b0883238c278eeb573e077 '));
$memcache->set (' aaaa ', ' hello everyone ');
Var_dump ($memcache->get (' aaaa '));
?>


'll see
String (PNS) "test|i:1177556731; test3|i:1177556881; "
This output proves that the session is working properly.
Using Memcache to store sessions can be much faster than files when reading and writing, and it is convenient to have multiple servers sharing sessions, which are configured to use the same set of memcached servers, reducing the additional effort. The disadvantage is that the session data are stored in memory, the persistence of the lack of, but the session data is not a big problem.
===================================
In general, the Session is stored as a text file on the server side. If you use Seesion, or if the PHP file calls the session variable, you must start it before calling the session and use the Session_Start () function. Others do not need you to set up, PHP automatically complete the Session file creation. The storage path of its default Session is the system Temp folder of the server.
However, if the sesstion of large data is encountered, the use of file-based session access bottlenecks may be in the disk IO operation, now using memcached to save session data, directly through the memory of the way, the efficiency naturally can improve a lot. The read and write speed is much faster than the files, and it is convenient to have multiple servers sharing the session, which is configured to use the same set of memcached servers, which reduces the additional effort.

The disadvantage is that the session data is stored in memory, once the outage, the data will be lost. However, the session data is not a serious problem.
How to use memcached to store a session? The following are the basic configuration steps:
1. Installing memcached
The "Registered save handlers" in the Phpinfo output will have "files User SQLite".

2. Modify the configuration file,
A. Global settings in php.ini (* Requires server restart)
Session.save_handler = Memcache
Session.save_path = "tcp://127.0.0.1:11211"
B. Or a directory under the. htaccess:
Php_value Session.save_handler "Memcache"
Php_value Session.save_path "tcp://127.0.0.1:11211"
C. can also be in one application:
Ini_set ("Session.save_handler", "memcache");
Ini_set ("Session.save_path", "tcp://127.0.0.1:11211");
Note: the use of multiple memcached servers is separated by commas "," and, as described in the memcache::addserver () documentation, can take additional parameters "persistent", "weight", " Timeout "," Retry_interval "and so on, like this:" Tcp://host:port?persistent=1&weight=2,tcp://host2:p Ort2″.

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

The code is as follows:
<?php
set_session.php
Session_Start ();
if (!isset ($_session[' admin ')) {
$_session[' TEST ' = ' wan ';
}
Print $_session[' admin ';
print "\ n";
Print session_id ();
?>


5. Use SessionID to check the memcached.

The code is as follows:
<?php
get_session.php
$mem = new Memcache;
$mem->connect ("127.0.0.1", 11211);
Var_dump ($mem->get (' 0935216dbc0d721d629f89efb89affa 6 '));
?>

The code is as follows:
[Email protected] html]#/usr/local/webserver/php/bin/php-f get_session.php


Output Result:
String (16)
"Admin|s:3:" Wan ";"
Prove that the session is working properly.
===========================
Using Memcache to store sessions at read and write speeds should be much faster than files, and it would be convenient to have multiple servers with a shared session, which would be configured to use the same set of memcached servers, reducing the additional workload. The disadvantage is that session data is stored in memory and cannot be persisted, and if you want to persist storage, consider using Memcachedb to store it, or use the Tokyo Tyrant+tokyo cabinet to store it.

How do you judge if the session fails? In PHP.ini, there is a session.cookie_lifetime option, which represents SessionID the time the client cookie is stored, the default value is "0", which means that the browser is closed and SessionID is invalidated. This is true regardless of whether the session saved in the memcached is still valid (the session stored in the memcached is processed using memcached's internal mechanism, even if the session data is not invalidated and the client's SessionID is invalidated , so this key basically will not have the opportunity to use, using the memcached LRU principle, if the memcached memory is not enough, the new data will replace the outdated and oldest unused data), because SessionID has failed, So the client will regenerate a new sessionid.

The data stored in memcached is no longer than 30 days, which is based on the time of Operation Memcached, that is, as long as key is the original key, if you re-related to this key operation (such as set operation), and reset the validity period, The validity period of the data corresponding to this key is recalculated, as explained in the PHP manual

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

Memcached the main cache mechanism is the LRU (least recently used) algorithm + timeout failure. When you save data to memcached, you can specify how long the data can stay in the cache. If Memcached's memory is not enough, the expired slabs will be replaced first, then the oldest unused slabs.
===========================
In order for a Web application to use a large-scale access to the SaaS model, the application's cluster deployment must be implemented. To realize the cluster deployment, we need to implement the session sharing mechanism so that the sessions of multiple application servers are unified. Most services such as Tomcat use session replication technology to share the session.
Session Replication Technology issues:
(1) The technology is complex and must be done between the same middleware (e.g., tomcat-tomcat).
(2) In the case of continuous increase of the node, the performance loss caused by session replication will increase rapidly. Especially when the session has a larger object, and the object changes quickly, the performance decreases more significantly. This feature limits the horizontal scaling of Web applications.

Session sharing another way of thinking is to focus on the session management, the first thought is to use a database to centralize storage session, but the database is the file storage relative memory is one order of magnitude slower, At the same time this is bound to increase the burden of the database system. So a service that is fast and centrally stored is needed, so I think of memcached.

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

Memcached, are you quick?
Very fast. Memcached uses libevent (using Epoll under Linux if possible) to equalize any number of open links, use non-blocking network I/O, and implement reference counting for internal objects (so objects can be in various states for multiple clients). Use your own page block allocator and hash table, so virtual memory is not fragmented and the time complexity of virtual memory allocation is guaranteed to be O (1).
Use the process to pay attention to a few questions and improve ideas:
1, memcache memory should be large enough so that there will be no user session removed from the cache (you can close the Memcached object exit mechanism).
2, if the session read more than write, you can add a Oscache and other local cache before memcache, reduce the memcache read operation, thereby reducing network overhead, improve performance.
3, if the user is very many, you can use the Memcached group, through the set method with Hashcode, inserted into a memcached server
There are several scenarios for clearing the session:
(1) The memcached can be emptied at least once in the morning. Simple
(2) The object stored in the cache is set to an expiration time, the SessionID value is obtained through the filter, and the objects in the memcached are refreshed periodically. Objects that have not been refreshed for a long time are automatically cleared. (relatively complex, consuming resources)

Memcache storage session based on PHP (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.