Shorida (Krazynio at hotmail.com), 2006.04. 06, reprint please indicate the source
Introduction of Memcached
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
The first is the 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:
Copy Code code as follows:
# 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
After the installation is complete, memcached should be in/usr/bin/memcached.
third, run the memcached daemon
Running the memcached daemon is simple, with just one command line, no configuration files to modify (and no configuration files to modify):
/usr/bin/memcached-d-M 128-l 192.168.1.1-p 11211-u httpd parameter explanation:
-D runs memcached in daemon (daemon) mode;
-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.
Iv. The working principle of memcached
First, memcached is run in a daemon to one or more servers, ready to accept client connection operations, clients can be written in a variety of languages, currently known client APIs 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
There are two ways to make PHP a memcached client, invoking Memcached services for object access.
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 character 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 the memcached-client.php, after downloading the memcached-client.php, you can use the class "memcached" in this file to operate the memcached service. In fact, the code call is very simple, the main use of the method has add (), get (), replace () and delete (), the method described below:
add ($key, $val, $exp = 0)
Writes an object to the memcached, $key is the object's unique identifier, $val is the object data written, $exp is the expiration time, the unit is seconds, and the default is unlimited time;
get ($key)
Obtaining the object data from the memcached, $key obtaining by the unique identifier of the object;
replace ($key, $value, $exp=0)
Use $value to replace the contents of an object in the memcached with the $key identifier, which, like the Add () method, 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:
<?php
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:
<?php
$sql = ' SELECT * from users ';
$key = MD5 ($sql); Memcached Object identifier
if (!) ( $datas = $MC->get ($key))) {
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);
} else {
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.
V. Related Resources
- memcached official website
- PHP memcached Client
- Download memcached-client.php