memcached introduction In many occasions, we will hear the name memcached, but many students just heard, and did not use or actually understand, only know it is a very good stuff. Here is a brief introduction, memcached is an efficient and fast distributed memory object caching system, mainly used to speed up WEB dynamic applications. Second, memcached installation is the first download memcached, the latest version is 1.1.12, directly from the official website can be downloaded to memcached-1.1.12.tar.gz. In addition, memcached used the libevent, I downloaded is the libevent-1.1a.tar.gz. The next step is to unpack, compile, and install libevent-1.1a.tar.gz and memcached-1.1.12.tar.gz separately: # TAR-XZF libevent-1.1a.tar.gz
# CD LIBEVENT-1.1A
#./configure--PREFIX=/USR
# make
# make Install
# CD ...
# TAR-XZF Memcached-1.1.12.tar.gz
# CD memcached-1.1.12
#./configure--PREFIX=/USR
# make
# Make install installation is complete, memcached should be in/usr/bin/memcached. Third, run the memcached daemon running the memcached daemon is simple, just one command line, no need to modify any configuration file (and no configuration file for you to modify):/usr/bin/memcached-d-M 128-l 192.168.1.1- P 11211-u httpd parameter explanation:-D in the daemon (daemon) mode to run memcached;
-M sets the amount of memory that memcached can use, in m;
-L Sets the IP address of the listener, which, if it is native, can usually be set without this parameter;
-P Sets the listening port, the default is 11211, so you can also not set this parameter;
-u Specifies the user, and you need to specify the user using this parameter if you are currently root. Of course, there are other parameters can be used, man memcached can be seen. Four, memcached work principle first memcached is to run in a daemon way in one or more servers, at any time to accept client connection operations, clients can be written in a variety of languages, currently known client API including perl/php/python/ruby/ Java/c#/c and so on. PHP and other clients in connection with the Memcached service, the next thing is to access objects, each accessed object has a unique identifier key, access operations through this key, saved to the Memcached object is actually placed in memory, is not stored in the cache file, which is why memcached can be so efficient and fast. Note that these objects are not persistent and the data inside will be lost after the service is stopped. Third, how PHP as a memcached client has two ways to make PHP as a memcached client, invoke memcached services for object access operations. First, PHP has an extension called memcache, Linux needs to be compiled with the –enable-memcache[=dir] option, Window under the php.ini to remove Php_memcache.dll the front of the annotation to make it available. In addition, there is a way to avoid the expansion, recompilation of the trouble, that is, the direct use of php-memcached-client. This article chooses the second way, although the efficiency will be slightly worse than the extension library, but the question is not big. Four, PHP memcached application example first download memcached-client.php, after downloading the memcached-client.php, you can through this file class "memcached" to the memcached service operation. In fact, the code call is very simple, the main use of the method has add (), get (), replace () and delete (), as described in the following method: Add ($key, $val, $exp = 0)
Writes an object to the memcached $key is the unique identifier of the object, $val is the object data written, $exp is the expiration time, the unit is seconds, and the default is unlimited time; get ($key)
Gets the object data from the memcached, $key obtained by the unique identifier of the object; replace ($key, $value, $exp =0)
Use $value to replace the contents of an object in the memcached that is $key, as with the Add () method, which works only if the $key object exists; Delete ($key, $time = 0)
Deletes an object in the memcached that has an identifier of $key, $time an optional parameter, indicating how long it will take to wait before the deletion. The following is a simple test code that accesses the object data with the identifier ' MyKey ' in the code:
Copy Code code as follows:
Contains memcached class files
Require_once (' memcached-client.php ');
Option settings
$options = Array (
' Servers ' => array (' 192.168.1.1:11211 '),//memcached service address, port, multiple array elements can be used to represent more than one memcached service
' Debug ' => true,//whether to turn on debug
' Compress_threshold ' => 10240,//compressed with more than the number of bytes of data
' Persistant ' => false//whether to use persistent connection
);
Create a Memcached object instance
$MC = new memcached ($options);
Set the unique identifier used by this script
$key = ' MyKey ';
Writing objects to the memcached
$MC->add ($key, ' some random strings ');
$val = $MC->get ($key);
echo "n". Str_pad (' $MC->add () ', 60, ' _ '). " n ";
Var_dump ($val);
Replace the object data value that has been written
$MC->replace ($key, Array (' some ' => ' haha ', ' array ' => ' xxx '));
$val = $MC->get ($key);
echo "n". Str_pad (' $MC->replace () ', 60, ' _ '). " n ";
Var_dump ($val);
Delete an object in memcached
$MC->delete ($key);
$val = $MC->get ($key);
echo "n". Str_pad (' $MC->delete () ', 60, ' _ '). " n ";
Var_dump ($val);
?>
is not very simple, in practical applications, the result set of the database query is usually saved to the memcached, the next visit directly from the memcached, and no longer do the database query operations, which can greatly reduce the burden of the database. The value after the SQL statement MD5 () is typically used as the unique identifier key. Below is an example of caching a database query result set using memcached (this code fragment immediately follows the example code above):
Copy Code code as follows:
$sql = ' SELECT * from users ';
$key = MD5 ($sql); Memcached Object identifier
{
When cached data is not obtained in memcached, a database query is used to get the recordset.
echo "n". Str_pad (' Read datas from MySQL. ', 60, ' _ '). " n ";
$conn = mysql_connect (' localhost ', ' test ', ' test ');
mysql_select_db (' Test ');
$result = mysql_query ($sql);
while ($row = Mysql_fetch_object ($result))
$datas [] = $row;
Saves the result set data obtained in the database to memcached for use on the next visit.
$MC->add ($key, $datas);
{
echo "n". Str_pad (' Read datas from memcached. ', 60, ' _ '). " n ";
}
Var_dump ($datas);
?>
It can be seen that the use of memcached, you can reduce the database connection, query operations, the database load down, the speed of the script also improved. I have previously written a "PHP implementation of multiple server sharing session data" article, the text of the session is used to save the database, in the concurrent access to large, the server load will be very large, often exceeding the maximum number of MySQL connections, using memcached, We can solve this problem very well, the working principle is as follows:
When the user accesses the Web page, see if there is a session data for the current user in the memcached, use session_id () as the unique identifier, or if the data exists, return directly if it does not exist, then make a database connection, get the session data, and save the data to Memcached, for next use;
At the end of the current PHP run (or Session_write_close ()), the My_sess::write () method is invoked to write the data to the database, so that each time there is still a database operation, the method needs to be optimized. Use a global variable to record the session data when the user enters the page, and then compare the data in the write () method with the same session data that you want to write, to make a database connection, write to the database, and delete the corresponding object in the memcached. If the same, it means that the session data has not changed, so you can do nothing, directly returned;
Then how to solve the user session expiration time? Remember the memcached Add () method has an expiration time parameter $exp? The parameter value is set to less than the session maximum survival time. And don't forget to give those who have been online the duration of the session, which can be resolved in the Write () method, and the database data is updated by judging the time and complying with the criteria.