Using Memcache storage session based on PHP _php tips

Source: Internet
Author: User
Tags memcached php session 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 '));
?>

'll see
String (Panax) "test|i:1177556731; test3|i:1177556881; "
This output proves that the session is working properly.
Storing sessions with Memcache is much faster than files, and it is easier to share sessions with multiple servers, and configuring them 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.
===================================
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 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, the 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 is that the session data is stored in the memory, and once the downtime, the data will be lost. But it is not a serious problem for the session data.
How to use memcached to store the session? The following are the 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 Results:
String (16)
"Admin|s:3:" Wan ";"
Prove that the session is working correctly.
===========================
Storing sessions with memcache should be a lot faster than files in reading and writing, and 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 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 to judge the session invalidation? There is a session.cookie_lifetime option in the php.ini, which represents SessionID at the time the client cookie is stored, and the default is "0", which, on behalf of the browser, closes and the SessionID is invalidated. This does not matter whether the session saved in memcached is still valid (the session saved in Memcached is processed using the internal mechanism of the memcached, even if the session data is not invalidated and because the client's SessionID has expired) , 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 outdated and the oldest unused data, because the SessionID has been invalidated, So a new SessionID is regenerated at the client.

The data stored in the memcached is no longer than 30 days, the time is based on the operation Memcached time, that is, as long as the key or the original key, if you re to this key related operations (such as set operations), and reset the expiration date, Then the validity of the data for this key will be 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, but in the latter case the number of SE Conds may isn't exceed 2592000 (days).

The main cache mechanism of 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, it is necessary to implement a clustered deployment of the application. In order to realize the cluster deployment, it is necessary to implement session sharing mechanism, which makes the conversation unified among multiple application servers. Most services, such as Tomcat, use the session replication technology to realize session sharing.
problem with session replication technology:
(1) Technical complexity, must be completed between the same middleware (such as: 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.

Session sharing another way of thinking is to focus on the session management, the first thought is to use a database to centrally store session, but the database is file storage relative memory slow down an order of magnitude, At the same time, this will increase the burden of the database system. So we need a fast and remote centralized storage service, so I thought 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.