SoFunction
Updated on 2025-03-10

PHP memory cache function memcached example

The following briefly introduces the application example of the memcached class, which has certain reference value. Interested friends can refer to it.

1. Introduction to memcached

On many occasions, we will hear the name memcached, but many students have only heard of it, and have not used it or actually learned about it. They only know that it is a very good thing. Here I briefly introduce it, memcached is an efficient and fast distributed memory object cache system, mainly used to accelerate WEB dynamic applications.

2. Memcached installation

First, download memcached. The latest version is 1.1.12. You can download memcached-1.1. directly from the official website. In addition, memcached uses libevent, and I downloaded libevent-1.

Next, unpack libevent-1. and memcached-1.1., respectively:

# tar -xzf libevent-1.
# cd libevent-1.1a
# ./configure --prefix=/usr
# make
# make install
# cd ..
# tar -xzf memcached-1.1.
# cd memcached-1.1.12
# ./configure --prefix=/usr
# make
# make install

After the installation is complete, memcached should be in /usr/bin/memcached.

3. Run the memcached daemon

Running the memcached daemon is simple, it only requires a command line, and there is no need to modify any configuration files (and no configuration files are modified for you):
/usr/bin/memcached -d -m 128 -l 192.168.1.1 -p 11211 -u httpd

Parameter explanation:

  • -d Run memcached in daemon mode;
  • -m Sets the memory size that memcached can use, in M;
  • -l Set the IP address of the listening. If it is the local machine, this parameter can usually be not set;
  • -p Set the listening port, the default is 11211, so this parameter can also be not set;
  • -u Specify the user. If it is currently root, you need to use this parameter to specify the user.

Of course, there are other parameters that can be used, and you can see it in a moment if you want to use memcached.

4. The working principle of memcached

First of all, memcached runs on one or more servers in a daemon-like manner, accepts client connection operations at any time. The client can be written in various languages. Currently known client APIs include Perl/PHP/Python/Ruby/Java/C#/C, etc. After PHP and other clients establish a connection with the memcached service, the next thing is to access the object. Each accessed object has a unique identifier key. The access operation is carried out through this key. The objects saved in memcached are actually placed in memory, not in cache file. This is also the reason why memcached can be so efficient and fast. Note that these objects are not persistent, and after the service is stopped, the data inside will be lost.

5. How to use PHP as a memcached client

There are two ways to make PHP as the memcached client and call the memcached service for object access operations.

The first type is that PHP has an extension called memcache. When compiling in Linux, you need to bring the --enable-memcache[=DIR] option. Under Window, remove the comments before php_memcache.dll to make it available.

In addition, there is another way to avoid the troubles caused by extension and recompilation, which is to directly use php-memcached-client.

This article uses the second method. Although the efficiency is slightly worse than that of the extension library, it is not a big problem.

6. PHP memcached application example

First, download it. After downloading it, you can operate the memcached service through the class "memcached" in this file. In fact, the code calls are very simple. The main methods you can use are add(), get(), replace() and delete(). The method description is as follows:

add ($key, $val, $exp = 0)

Write an object into 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)

Get object data from memcached and get it through the object's unique identifier $key;

replace ($key, $value, $exp=0)

Use $value to replace the object contents of the object with the identifier $key in memcached. The parameters are the same as the add() method and will only work if the $key object exists;

delete ($key, $time = 0)


Delete an object in memcached with the identifier $key, and $time is an optional parameter, indicating how long you need to wait before deletion.

The following is a simple test code, which accesses the object data with the identifier 'mykey':

<?php 
// Contains the memcached class filerequire_once(''); 
// Option settings$options = array( 
 'servers' => array('192.168.1.1:11211'), //The address and port of the memcached service can be used to represent multiple memcached services 'debug' => true, //Whether to open the debug 'compress_threshold' => 10240, //Compress when more than how many bytes of data are compressed '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'; 
// Write objects into memcached$mc->add($key, 'some random strings'); 
$val = $mc->get($key); 
echo "n".str_pad('$mc->add() ', 60, '_')."n"; 
var_dump($val); 
// Replace 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 object in memcached$mc->delete($key); 
$val = $mc->get($key); 
echo "n".str_pad('$mc->delete() ', 60, '_')."n"; 
var_dump($val); 
?>

Isn't it very simple? In practical applications, the result set of database queries is usually saved in memcached, and the next time you access it, it will directly get it from memcached, and no longer do database query operations, which can greatly reduce the burden on the database. The value after the SQL statement md5() is usually used as the unique identifier key. Below is an example of using memcached to cache database query result sets (this code snippet follows the above example code):

<?php 
$sql = 'SELECT * FROM users'; 
$key = md5($sql); //memcached object identifier{ 
 // No cached data is obtained in memcached, the record set is obtained using 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 obtained from the database into memcached for use the next time you access it. $mc->add($key, $datas); 
{ 
 echo "n".str_pad('Read datas from memcached.', 60, '_')."n"; 
} 
var_dump($datas); 
?> 

It can be seen that after using memcached, database connection and query operations can be reduced, the database load is loaded, and the script runs faster.

I once wrote an article titled "PHP Implements Multi-Server Sharing SESSION Data". The SESSION in the article is saved using a database. When there are large concurrent visits, the server load will be very high, and it will often exceed the maximum number of MySQL connections. Using memcached, we can solve this problem well. The working principle is as follows:

  • When a user visits a web page, check whether there is the SESSION data of the current user in memcached, and use 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, obtain the SESSION data, and save this data to memcached for next use;
  • When the current PHP run ends (or uses session_write_close()), the My_Sess::write() method will be called to write the data to the database. In this way, there will still be database operations every time, and this method also needs to be optimized. Use a global variable to record the SESSION data when the user enters the page, and then compare whether this data is the same as the SESSION data to be written in the write() method. Only when the database is connected and written to the database is different, and the corresponding object in memcached is deleted. If the same, it means that the SESSION data has not changed, so you can do nothing and return it directly;
  • So how to solve the expiration time of user SESSION? Remember that the add() method of memcached has an expiration time parameter $exp? Set this parameter value to be less than the maximum survival time of SESSION. Also, don’t forget to extend the SESSION time to those users who have been online. This can be solved in the write() method. By judging the time, the database data will be updated if the conditions meet.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.