PHP Memcached application implementation code

  • 2020-03-31 20:21:11
  • OfStack

Xiao lida (KrazyNio AT hotmail.com), 2006.04.06

I. introduction to memcached

On many occasions, we'll hear the name (link: http://www.danga.com/memcached/), but many students just heard, and have not used or real understand, only know that it is a good thing. To give you a quick overview, memcached is an efficient and fast distributed memory object caching system for accelerating dynamic WEB applications.

Ii. Memcached installation

First of all is to download memcached, the latest version is 1.1.12, directly from the official website to download the (link: http://www.danga.com/memcached/dist/memcached-1.1.12.tar.gz). In addition, memcached is used (link: http://monkey.org/~provos/libevent/), and I (link: http://monkey.org/~provos/libevent-1.1a.tar.gz).

Next, 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 

Once installed, memcached should be at /usr/bin/memcached.

Run the memcached daemon

Running the memcached daemon is as simple as a single command line, and you don't need to change any configuration files (no configuration files for you to change) :

/usr/bin/memcached-d-m 128-l 192.168.1.1-p 11211-u HTTPD parameter explanation:

-d run memcached as a daemon;
-m set the memory size memcached can use, in m;
-l set the IP address of the monitor, if it is a native, usually can not set this parameter;
-p set the listening port, the default is 11211, so you can not set this parameter;
-u specifies the user, which you need to specify if you are currently root.
Of course, there are other parameters you can use, as you can see from man memcached.

Iv. How memcached works

First way is memcached daemon running on one or more servers, operation at any time to accept the client's connection, the client can by all sorts of languages, are now known to the client API including Perl/PHP/Python/Ruby/Java/C # / C etc. PHP with memcached client services such as after the connection is established, and the next thing is to access the object, access to each object has a unique identifier key, access operations are conducted through the key, save to the object in the memcached is actually placed in memory, and is not stored in the cache file, this is also why memcached could be so efficient and fast. Note that these objects are not persistent, and when the service is stopped, the data inside is lost.
The < img border = 0 id = image622 Alt = image001. PNG SRC = "http://files.jb51.net/upload/2010-2/20100208093610631.png" >

Iii. How to use PHP as the memcached client

There are two ways to have PHP act as a memcached client, calling the memcached service for object access operations.

The first kind, PHP has a place called (link: http://www.php.net/manual/en/ref.memcache.php), under Linux compile-time need take � enable - memcache [= DIR] options, under the Window is in PHP. The ini removed php_memcache. DLL's comment in front, so that it is available.

Besides, there are also a kind of method, can avoid the trouble brought by the extension, recompile, that is, directly use (link: http://wikipedia.sourceforge.net/doc/memcached-client/_includes_memcached-client_php.html).

This article USES the second approach, which is slightly less efficient than the extended library, but not a big deal.

Iv. Example of PHP memcached application

First (link: http://www.nioxiao.com/wp-content/uploads/2006/04/memcached-client.zip), in the download memcached - client. PHP, can be used on class "memcached" in this file the memcached service operation. In fact, the code call is very simple, and the main methods used are add(), get(), replace() and delete(). The method description is as follows:

add ($key, $val, $exp = 0)
Write an object to memcached, $key is the unique identifier of the object, $val is the written object data, $exp is the expiration time, the unit is seconds, the default is unlimited time;

The < code > get ($key) < / code >
Get the object data from memcached by the object's unique identifier $key;

The < code > replace ($key, $value, $exp = 0) < / code >
Use $value to replace the contents of the memcached object with the identifier $key. The parameter is the same as the add() method.

delete ($key, $time = 0)
Remove the object in memcached with the identifier $key, and $time is an optional parameter that indicates how long to wait before deleting it.

Here is a simple test code to access the object data with the identifier 'mykey' :


<?php 
//Contains the memcached class file
require_once('memcached-client.php'); 
//Option is set
$options = array( 
'servers' => array('192.168.1.1:11211'), //The address and port of the memcached service, which can be represented by multiple array elements
'debug' => true, //Whether to turn on debug
'compress_threshold' => 10240, //More than how many bytes of data to compress
'persistant' => false //Whether to use a persistent connection
); 
//Create an instance of the memcached object
$mc = new memcached($options); 
//Sets the unique identifier used by this script
$key = 'mykey'; 
//Write objects to memcached
$mc->add($key, 'some random strings'); 
$val = $mc->get($key); 
echo "n".str_pad('$mc->add() ', 60, '_')."n"; 
var_dump($val); 
//Replaces the written object data value
$mc->replace($key, array('some'=>'haha', 'array'=>'xxx')); 
$val = $mc->get($key); 
echo "n".str_pad('$mc->replace() ', 60, '_')."n"; 
var_dump($val); 
//Delete the objects in memcached
$mc->delete($key); 
$val = $mc->get($key); 
echo "n".str_pad('$mc->delete() ', 60, '_')."n"; 
var_dump($val); 
?> 

Isn't that simple? In practice, it's common to save the result set of a database query to memcached, and then get it directly from memcached the next time you visit, rather than doing a database query, which can greatly reduce the burden on the database. The value after the SQL statement md5() is typically used as the unique identifier key. Here is an example of using memcached to cache the result set of a database query (this code snippet follows the example above) :
 
<?php 
$sql = 'SELECT * FROM users'; 
$key = md5($sql); //Memcached object identifier
if ( !($datas = $mc->get($key)) ) { 
//If no cached data is retrieved in memcached, the recordset is retrieved using a database query.
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; 
//Save the result set data from the database to memcached for next access.
$mc->add($key, $datas); 
} else { 
echo "n".str_pad('Read datas from memcached.', 60, '_')."n"; 
} 
var_dump($datas); 
?> 

As you can see, with memcached, database connections and queries are reduced, database load is reduced, and scripts run faster.

Before I wrote an article called (link: http://www.nioxiao.com/sharing-php-session-data-between-servers/), the SESSION is to use a database to store, in concurrent traffic great the server load will be very big, often out of MySQL maximum number of connections, use memcached, we can solve this problem well, principle of work is as follows:

When a user visits a web page, check whether there is the current user's SESSION data in memcached, using session_id() as the unique identifier; If the data exists, it will be returned directly. If it does not exist, then make a database connection, get the SESSION data, and save the data to memcached for the next time. (or use the end of the current PHP run (link: http://php.liukang.com/manual/en/function.session-write-close.php)), is called My_Sess: : write () method, to write data into the database, in this way, each time there could still be database operations, and for this method, also need to be optimized. Use a global variable, record the user enter the page of the SESSION data, and then in the write () method in comparing this data and want to write to the SESSION data are the same, for different database connections, written to the database, delete the corresponding objects in memcached at the same time, if the same, has said the SESSION data did not change, you can not do any operation, direct return; So what about the user SESSION expiration time? Remember that memcached's add () method has an expiration time parameter of $exp? Set this parameter value to be less than the SESSION maximum lifetime. Also, don't forget to extend the SESSION length to users who are always online, which can be solved in the write() method by determining the time and updating the database if they are qualified.

V. related resources

(link: http://www.danga.com/memcached/) (link: http://wikipedia.sourceforge.net/doc/memcached-client/_includes_memcached-client_php.html) (link: http://www.nioxiao.com/wp-content/uploads/2006/04/memcached-client.zip)

Related articles: