Explanation of using memcache to store sessions based on php _ PHP Tutorial

Source: Internet
Author: User
Explanation of using memcache to store sessions based on php. The PHP sessions of the web server are all sent to memcached, so that no matter which web server you allocate the ip connection to by the distributor, the configuration method is very simple, in the php configuration file, the php sessions of the web server are all sent to memcached, so no matter which web server the distributor assigns the ip connection to, the configuration method is very simple, in the php configuration file.
Add a statement, but you must install the memcache module.

1. set the session to use memcache for storage
Method I: global settings in php. ini
Session. save_handler = memcache
Session. save_path = "tcp: // fig: 11211"
Method II:. htaccess in a directory:
Php_value session. save_handler "memcache"
Php_value session. save_path "tcp: // fig: 11211"
Method III: or in an application:
Ini_set ("session. save_handler", "memcache ");
Ini_set ("session. save_path", "tcp: // 127.0.0.1: 11211 ");
Multiple memcached servers are separated by commas (,), which are the same as those described in the Memcache: addServer () document, you can include additional parameters such as "persistent", "weight", "timeout", and "retry_interval". for example, "tcp: // host1: port1? Persistent = 1 & weight = 2, tcp: // host2: port2 ".
If the installed PECL is memcached (which uses the libmemcache Library), the configuration should be
Ini_set ("session. save_handler", "memcached"); // it indicates that memcached is not memcache.
Ini_set ("session. save_path", "127.0.0.1: 11211"); // do not use tcp:

2. start memcached:
Memcached-d-l 127.0.0.1-p 11212-m 128
Or start the Memcache server:
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
-D option is to start a daemon,
-M indicates the amount of memory allocated to Memcache. the unit is MB. here is 100 MB,
-U is the user who runs Memcache. here I am root,
-L is the IP address of the listening server. if there are multiple IP addresses, I have specified the IP address 192.168.36.200,
-P is the port for Memcache listening. I have set port 11211 here, preferably port 1024 or above. We use port 11211 here.
-The "c" option is the maximum number of concurrent connections. the default value is 1024. I have set 256 here, which is based on the load of your server.
-P is the pid file for saving Memcache. here I save it in/tmp/memcached. pid,

3. use memcache in the program for session storage
Use an example to test:

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:

The code is as follows:


$ Memcache = memcache_connect ('localhost', 11211 );
Var_dump ($ memcache-> get ('19216821213c65cedec65b0883238c278eeb573e077 '));
$ Memcache-> set ('AAA', 'hello everyone ');
Var_dump ($ memcache-> get ('aaa '));
?>


You will see
String (37) "TEST | I: 1177556731; TEST3 | I: 1177556881 ;"
This output proves that the session works normally.
Using memcache to store sessions is much faster in reading and writing than when using files, and it is more convenient when multiple servers need to share sessions, you can configure these servers to use the same group of memcached servers, reducing the additional workload. The disadvantage is that session data is stored in memory, which lacks persistence, but it is not a big problem for session data.
==========================================
Generally, sessions are stored on the server as text files. If you use Seesion or the PHP file needs to call the Session variable, you must start the Session before calling it and use the session_start () function. PHP automatically creates the Session file. The default Session storage path is the temporary system folder of the server.
However, if you encounter Sesstion with a large amount of data, the bottleneck of file-based Session access may be in disk I/O operations. now, Memcached is used to save Session data and the memory is used directly, efficiency can naturally be improved a lot. The speed of reading and writing is much faster than that of files, and it is more convenient for multiple servers to share sessions. you can configure these servers to use the same group of memcached servers, this reduces the additional workload.

The disadvantage is that session data is stored in memory, and data will be lost once it goes down. However, session data is not a serious problem.
How to use memcached to store sessions? The basic configuration steps are as follows:
1. install memcached
In the phpinfo output, "Registered save handlers" will have "files user sqlite ".

2. modify the configuration file,
A. set global settings in php. ini (* restart the server)
Session. save_handler = memcache
Session. save_path = "tcp: // fig: 11211"
B. or. htaccess in a directory:
Php_value session. save_handler "memcache"
Php_value session. save_path "tcp: // fig: 11211"
C. You can also:
Ini_set ("session. save_handler", "memcache ");
Ini_set ("session. save_path", "tcp: // 127.0.0.1: 11211 ");
Note:Multiple memcached servers are separated by commas (,), which are the same as those described in the Memcache: addServer () document, additional parameters such as "persistent", "weight", "timeout", and "retry_interval" can be included, such as: "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 the creation of a session

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 memcached.

The code is as follows:


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


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 ";"
This proves that the session works properly.
======================================
Using memcache to store sessions should be much faster in reading and writing than in files, and it is more convenient when multiple servers need to share sessions, you can configure these servers to use the same group of memcached servers, reducing the additional workload. The disadvantage is that session data is stored in the memory and cannot be stored persistently. if you want to store session data persistently, you can use Memcachedb for storage or use Tokyo Tyrant + Tokyo Cabinet for storage.

How can I determine if the session is invalid? In php. there is a Session in ini. cookie_lifetime indicates the time when SessionID is stored in the Cookie on the client. the default value is "0", indicating that SessionID will be voided once the browser is closed, in this way, no matter whether the Session stored in Memcached is valid or not (Sessions stored in Memcached are processed using the internal mechanism of Memcached. even if the session data is not invalid, the SessionID of the client has expired, therefore, this key will basically not be used. if Memcached's memory is insufficient, the new data will replace the expired and oldest unused data). because the SessionID has expired, a new SessionID will be generated on the client.

The data stored in Memcached cannot exceed 30 days. this time is based on the time when Memcached is operated. that is to say, as long as the key is still the original key, if you re-operate the key (such as set operation) and re-set the validity period, the validity period of the data corresponding to the key will be re-calculated, which is described in the php Manual.

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 LRU (least recently used) algorithm + timeout failure. When you store data in memcached, you can specify how long the data can be cached. If memcached memory is not enough, expired slabs will be replaced first, and then it will be the oldest unused slabs.
======================================
To enable large-scale access to web applications in saas mode, cluster deployment of applications must be implemented. to achieve cluster deployment, you must implement the session sharing mechanism so that sessions are unified among multiple application servers. most services such as tomcat use session replication technology to share sessions.
Session replication technology problems:
(1) the technology is complex and must be completed between the same middleware (for example, between tomcat and tomcat ).
(2) when the number of nodes continues to increase, the performance loss caused by session replication will rapidly increase. especially when a large object is saved in the session, and the object changes rapidly, the performance decline is more significant. this feature limits the horizontal scaling of web applications.

Another idea of session sharing is to centralize session management. The first thought is to use a database to store sessions in a centralized manner, but the database is an order of magnitude slower than the memory, at the same time, this will inevitably increase the burden on the database system. therefore, we need a fast and remote centralized storage service, so we thought of memcached.

What can memcached cache?
By maintaining a unified and huge hash table in the 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 (if possible, epoll is used in linux) to balance any number of open links and use non-blocking network I/O, implement reference counting on internal objects (therefore, objects can be in a variety of states for various clients), and use your own page block distributor and hash table, therefore, the virtual memory will not produce fragments, and the time complexity of virtual memory allocation can be ensured to be O (1 )..
Pay attention to several issues and improvement ideas during use:
1. memcache memory should be large enough to prevent the user session from being cleared from the Cache (you can disable the memcached object exit mechanism ).
2. if the session reads much more data than the write operations, you can add a local cache such as Oscache before memcache to reduce read operations on memcache, thus reducing network overhead and improving performance.
3. if there are many users, you can use the memcached group and insert it to a memcached server using the hashCode in the set method.
There are several solutions for clearing sessions:
(1) you can clear memcached at least once in the early morning. (Simple)
(2) set an expiration time for the objects stored in the cache, get the sessionId value through the filter, and regularly refresh the objects in memcached. objects not refreshed for a long time are automatically cleared. (relatively complex, resource consumption)

The reset session is all sent to memcached, so no matter which web server you allocate the ip connection to by the distributor, there will be no problem. The Configuration method is very simple, just in the php configuration file...

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.