Using Memcache to store session based on PHP

Source: Internet
Author: User
Tags hash ini memcached php file php session reset sessions tomcat

The PHP session of the Web server is given to memcached so that you do not have a problem with which Web server the Distributor will divide the IP connection to, and the configuration method is simple, in the PHP configuration file
Adding a statement is fine, but you need to install the Memcache module.

1. Set session to store with Memcache
method I: Global settings in php.ini
Session.save_handler = Memcache
Session.save_path = "tcp://127.0.0.1:11211"
Method II: A. htaccess under 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");
The use of multiple memcached servers is separated by commas "," and as described in the Memcache::addserver () document, with additional parameters such as "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 that uses 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 the 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 am 100MB here,
-U is the user running memcache, I am here root,
-L is a listening server IP address, if there are more than one address, I specify the IP address of the server 192.168.36.200,
-P is set memcache listening port, I set up here 11211, preferably more than 1024 of the port, 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 load of your server to set.
-P is set to save the Memcache pid file, which I am here to save in/tmp/memcached.pid,

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

Copy Code code 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. Use SessionID to memcached query:

Copy Code code as follows:


<?php


$memcache = memcache_connect (' localhost ', 11211);


Var_dump ($memcache->get (' 19216821213c65cedec65b0883238c278eeb573e077 '));


$memcache->set (' aaaa ', ' hello everyone ');


Var_dump ($memcache->get (' aaaa '));


?>

The


will see the
string (test|i:1177556731); test3|i:1177556881; "
This output proves that the session is working correctly.
Storing sessions with Memcache is much faster in reading and writing than files, and is more convenient when multiple servers need to share sessions, and configuring these servers to use the same set of memcached servers can reduce the extra effort. The disadvantage is that the session data are stored in the memory, there is a lack of persistence, but it is not a big problem for the session data.
===================================
Generally, 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 session and use the Session_Start () function. Other do not need you to set up, PHP automatically completes the session file creation. The default session path is the server's system Temp folder.
However, if you encounter a large amount of data sesstion, the use of file-based session access bottlenecks may be in the disk IO operation, now use memcached to save sessions data, directly through the memory of the way, efficiency naturally can improve a lot. The speed of reading and writing is much faster than files, and it is easier to share sessions with multiple servers, and configuring these servers to use the same set of memcached servers can reduce the extra effort. The disadvantage of

is that session data is stored in memory, and data will be lost once it is down. But it is not a serious problem for the session data.
How do I use memcached to store sessions? The following are basic configuration steps:
1. Install memcached
the "registered save handlers" in the Phpinfo output will have the "Files User SQLite".

2. Modify the configuration file,
A. Global settings in php.ini (* requires reboot of server)
Session.save_handler = memcache
Session.save_path = "tcp://127.0.0.1:11211"
B. Or a directory of. htaccess:
php_value Session.save_handler "Memcache"
Php_value Session.save_path "tcp://127.0.0.1:11211"
c. It can also be used 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 () document, you can take additional arguments "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 Create a session

Copy Code code as follows:


<?php


//set_session.php


session_start ();


if (!isset ($_session[' admin ')) {


$_session[' TEST ' = ' wan ';


}


print $_session[' admin '];


print "n";


print session_id ();


?>


5. Check with SessionID to memcached

Copy Code code as follows:


<?php


//get_session.php


$mem = new Memcache;


$mem->connect ("127.0.0.1", 11211);


Var_dump ($mem->get (' 0935216dbc0d721d629f89efb89affa 6 '));


?>

Copy Code code as follows:


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


output:
String (a)
Admin|s:3: WAN; The
proves that the session is working correctly.
===========================
Use Memcache to store the session should be much faster in reading and writing than files, and more convenient when multiple servers need to share sessions. By configuring these servers to use the same set of memcached servers, you can reduce the extra effort. The disadvantage is that the session data is stored in memory, not persistent storage, if you want to persist storage, you can consider using Memcachedb to store, or use Tokyo Tyrant+tokyo cabinet to store. How does

determine that the session fails? There is a session.cookie_lifetime option in the php.ini, which represents sessionid the time that the client cookie is stored, the default value is "0", which, on behalf of the browser, closes, and the SessionID is invalidated, so that it is saved in Whether the session in the memcached is still valid (sessions saved in memcached are processed using the internal mechanism of memcached, even if the session data is not invalidated, and because the client's SessionID is invalidated, So this key will basically not have the opportunity to use, using the memcached LRU principle, if memcached memory is not enough, the new data will replace the expiration and the oldest unused data, because the SessionID has been invalidated, so the client will regenerate a A new SessionID.

The maximum number of data saved in memcached is no longer than 30 days, which is based on the time of the operation Memcached, that is, if the key is the same as the original key, if you reset the key to the related operation (such as set operation), And the expiration date is reset, the validity of the data for 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. can also use Unix timestamp or a number of seconds sTarting from the "but in" latter case "the number of seconds may isn't exceed 2592000 (days). The main cache mechanism for the

Memcached 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 memory is not available, the expired slabs will be replaced first, then the oldest unused slabs.
===========================
In order for Web applications to use a large-scale access to SaaS mode, you must implement a clustered deployment of the application. To implement the cluster deployment, we need to implement the session sharing mechanism. It makes session unification between multiple application servers, and most services, such as Tomcat, are shared by sessions with replication technology. Problem with the
session replication technology:
(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 nodes, the performance loss caused by session replication will increase rapidly. Especially when a large object is saved in the session, and the object changes faster, the performance drop is more significant. This feature limits the level of Web application expansion. Another idea of the

session sharing is to centralize the session management, with the first thought of using a database to centrally store the session, but the database is one order of magnitude slower than the file storage relative memory, while This is bound to increase the burden of the database system. Therefore, a fast and remote centralized storage service is needed, so I think of memcached.

What can memcached cache?
by maintaining a unified, large 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 searches.

Memcached, are you quick?
very fast. Memcached uses libevent (if possible, use Epoll under Linux) to balance any number of open links, to use non-blocking network I/O, to implement reference counting on internal objects (therefore, for multiple clients, objects can be in a variety of states), Use your own page block allocator and hash table, so virtual memory is not fragmented and the time complexity of virtual memory allocations can be guaranteed to be O (1).
use the process to pay attention to several problems and improve the idea:
1, memcache memory should be large enough, so that no user session from the cache to be purged from the problem (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 operations, 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 the session cleanup:
(1) can be at least in the wee hours when the memcached do a clear. Simple
(2) The object saved in the cache sets an expiration time, gets the SessionID value through the filter, and periodically refreshes the objects in the memcached. Objects that have not been refreshed for a long time are automatically purged. (relatively complex, consuming resources)

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.