I. Introduction of Memcached
In many occasions, we will hear the name memcached, but many students just heard, and have not used or actually understand, only know it is a very good stuff. As a brief introduction, memcached is an efficient and fast distributed memory object caching system, which is mainly used to accelerate WEB dynamic applications.
Second, memcached installation
The first is to 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 to libevent, I downloaded is 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, respectively:
# 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 need to modify any configuration files (and no configuration files for you to modify):
/usr/bin/----192.168. 1.1-11211-u httpd
Parameter explanation:
-D run memcached;-m settings in the daemon (daemon) to set the amount of memory that memcached can use, in M; l to set the listening IP address, if this is the case, you can usually not set this parameter,-p set the listening port, the default is 11211, so also You can not set this parameter;-u specifies the user, if it is currently root, it needs to be specified by this parameter.
Of course, there are other parameters to use, man memcached can be seen.
Iv. working principle of memcached
First of all, memcached is running on one or more servers in the daemon mode, accepting the client's connection operation at any time, the client can be written in various languages, the currently known client API includes perl/php/python/ruby/java/c#/c and so on. PHP and other clients after establishing a connection with the Memcached service, the next thing is to access the object, each access to the object has a unique identifier key, access operations are through this key, the object saved to memcached is actually placed in memory, is not saved 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 is lost after the service is stopped.
V. How PHP acts as a memcached client
There are two ways to make PHP a memcached client, invoking Memcached's service for object access.
First, PHP has an extension called memcache, which needs to be compiled with the –enable-memcache[=dir] option under Linux, and Window will remove the annotation from the front of Php_memcache.dll in php.ini to make it usable.
In addition, there is a way to avoid the problem of scaling and recompiling, which is to use php-memcached-client directly.
This article chooses the second way, although the efficiency will be slightly worse than the expansion library, but the problem is not big.
Vi. examples of PHP memcached applications
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 is described as follows:
($key, $val,=0)
Writes an object to Memcached, $key is the unique identifier of the object, $val is the object data written, $exp the expiration time, in seconds, the default is unlimited time;
get ($key)
Gets the object data from the memcached, $key obtained by the object's unique identifier;
replace ($key, $value, $exp=0)
Use $value to replace object content with an identifier $key in memcached, as with the Add () method, which only works if $key object exists;
delete ($key, $time = 0)
Deletes an object with an identifier $key in memcached, $time as an optional parameter, indicating how long to wait before deleting.
The following is a simple test code that accesses object data with identifier ' MyKey ' in the code:
<?PhpContains the Memcached class fileRequire_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 multiple memcached services ' Debug ' = True, Whether to turn on debug ' Compress_threshold ' = 10240, Compression when more than a few bytes of data ' Persistant ' = False Whether to use persistent connections );Creating an Memcached object instance$mc= NewMemcached($options);Sets the unique identifier used by this script$key= ' MyKey ';Writing objects to the memcached$mc-Add($key, ' Some random strings ');$val=$mc-Get($key);EchoN.Str_pad(' $MC->add () ', 60, ‘_‘).N;Var_dump($val);Replace a written object data value$mc-Replace($key,Array(' Some '=' Haha ', ' Array '=' xxx '));$val=$mc-Get($key);EchoN.Str_pad(' $MC->replace () ', 60, ‘_‘).N;Var_dump($val);Delete an object in memcached $MC ->delete ( $key Span class= "pun"); $val = $MC ->get< Span class= "pun" > ( $key "n" . ( ' $MC->delete () ' , 60, ' _ ' ). " N "; Var_dump $val ?>
is not very simple, in the actual application, usually will save the result set of the database query to memcached, the next access is obtained directly from the memcached, and no longer does the database query operation, this can reduce the burden of the database to a great extent. Typically, the value after the SQL statement MD5 () is used as the unique identifier key. Below is an example of using memcached to cache a result set of a database query (the code snippet follows the example code above):
<?Php$sql= ' SELECT * from users ';$key=Md5($sql); Memcached Object identifiersIf ( ! ($datas=$mc-Get($key)) ) { If the cached data is not obtained in memcached, the recordset is obtained using a database query.EchoN.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" . ( ' Read datas from memcached. ' , 60, "n" ;}var_dump ( $datas ?>
As you can see, after using memcached, you can reduce database connection, query operations, database load down, scripts run faster.
I have previously written a "PHP implementation of multi-server sharing session Data" article, the session is saved using the database, when the concurrent access is large, the server load will be very large, often will exceed MySQL maximum connection number, using memcached, We can solve this problem very well and work in the following way:
When the user visits the Web page, see if the memcached has the current user's SESSION data, use SESSION_ID () as the unique identifier, if the data exists, then return directly, if it does not exist, the database connection, get SESSION data, and save this data to Memcached, for the next use; when the current PHP run ends (or uses session_write_close ()), the My_sess::write () method is called and the data is written to the database, so that each time there is still a database operation, for this method , and it needs to be optimized. A global variable is used to record the session data when the user enters the page, and then in the Write () method, the data is compared with the session data to be written, the database is connected, the database is written, and the corresponding object in the memcached is deleted. If the same, it means that the session data has not changed, then you can do nothing to return directly, then the user session expiration time how to solve it? Remember Memcached's Add () method has an expiration time parameter $exp? Set this parameter value to less than the maximum survival time of the SESSION. Also do not forget to the users who have been online for the duration of the SESSION, this can be resolved in the Write () method, by judging the time, meet the criteria to update the database data.
PHP using memcached detailed