PHP Memcached application implementation code_PHP tutorial

WBOY
Release: 2016-07-21 15:41:43
Original
795 people have browsed it

Xiao Lida (KrazyNio AT hotmail.com), 2006.04. 06, please indicate the source for reprinting

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 understood it. They only know that it is a very good thing. Here is a brief introduction: memcached is an efficient and fast distributed memory object caching system, mainly used to accelerate WEB dynamic applications.

2. Memcached installation

The first step is to download memcached. The latest version is 1.1.12. You can download it directly from the official website to memcached-1.1.12.tar.gz. In addition, memcached uses libevent, and I downloaded 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:

Copy the codeThe code is 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 installation is complete, memcached should be in /usr/bin/memcached.

3. Run the memcached daemon

Running the memcached daemon is very simple, just a command line, no need to modify any configuration files (there is no configuration file) Modified for you):

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

-d as daemon Run memcached in the mode;
-m sets the memory size that memcached can use, in M;
-l sets the listening IP address. If it is the local machine, this parameter usually does not need to be set;
-p Set the listening port, the default is 11211, so this parameter does not need to be set;
-u specifies the user. If you are currently root, you need to use this parameter to specify the user.
Of course, there are other parameters that can be used. You can see them by running man memcached.

4. How memcached works

First of all, memcached runs in one or more servers as a daemon, accepting client connection operations at any time. The client can Written in various languages, currently known client APIs include Perl/PHP/Python/Ruby/Java/C#/C and so on. After clients such as PHP establish a connection with the memcached service, the next thing is to access objects. Each accessed object has a unique identifier key. Access operations are performed through this key and saved to memcached. The objects in are actually placed in memory, not stored in cache files, 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.
image001.png

3. How to use PHP as memcached client

There are two ways to use PHP as a memcached client to call memcached services for object access operations.

First, PHP has an extension called memcache. When compiling under Linux, you need to bring the –enable-memcache[=DIR] option. Under Window, it is in php. Remove the comment in front of php_memcache.dll in ini to make it available.

In addition, there is another way to avoid the trouble caused by expansion and recompilation, and that is to use php-memcached-client directly.

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

4. PHP memcached application example

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

add ($key, $val, $exp = 0)
Write objects into memcached. $key is the unique identifier of the object, $val is the object data written, $exp is the expiration time in seconds, The default is no time limit;

get ($key)
Get object data from memcached through the unique identifier $key of the object;

replace ($key, $value, $exp=0)
Use $value to replace the object content with identifier $key in memcached. The parameters are the same as the add() method. It will only work if the $key object exists. ;

delete ($key, $time = 0)
Delete the object with identifier $key in memcached. $time is an optional parameter, indicating how long to wait before deleting.

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

Copy the code The code is as follows :

// Contains memcached class file
require_once('memcached-client.php');
// Option setting
$options = array(
'servers' => array('192.168.1.1:11211'), //The address and port of the memcached service. Multiple array elements can be used to represent multiple memcached services
'debug' => true, // Whether to turn on debug
'compress_threshold' => 10240, //Compress when the data exceeds the number of bytes
'persistant' => false //Whether to use persistent connections
);
/ / Create a memcached object instance
$mc = new memcached($options);
// Set the unique identifier used by this script
$key = 'mykey';
// Write to memcached Input object
$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 objects 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, database queries are usually The result set is saved to memcached, and the next time it is accessed, it is obtained directly from memcached without performing database query operations. This can reduce the burden on the database to a great extent. Usually the value after the SQL statement md5() is used as the unique identifier key. The following is an example of using memcached to cache the database query result set (this code snippet follows the sample code above):
Copy the code The code is as follows:

$sql = 'SELECT * FROM users';
$key = md5($sql); //memcached object identifier
if ( !($ datas = $mc->get($key)) ) {
// If cached data is not obtained in memcached, use database query to obtain the record set.
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 to memcached for use during the next access.
$mc->add($key, $datas);
} else {
echo "n".str_pad('Read datas from memcached.', 60, '_')."n ";
}
var_dump($datas);
?>

It can be seen that after using memcached, database connections and query operations can be reduced, the database load is reduced, and the running speed of the script is also improved.

I have written an article before called "PHP implements multi-server sharing of SESSION data" . The SESSION in the article is saved in a database. When the number of concurrent visits is large, the load on the server will increase. It is very large and often exceeds the maximum number of MySQL connections. Using memcached, we can solve this problem very well. The working principle is as follows:

  • When a user accesses a web page, check whether there is the current user's SESSION data 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 connect to the database to obtain the SESSION data, and Save this data to memcached for next use;
  • When the current PHP operation ends (or session_write_close() is used), the My_Sess::write() method will be called to write the data to the database. In this case, there will still be database operations every time , 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 this data in the write() method to see if it is the same as the SESSION data you want to write. If they are different, connect to the database and write it to the database. At the same time, add the corresponding data in memcached. If the objects are deleted, if they are the same, it means that the SESSION data has not changed, so you can return directly without doing any operation;
  • So how to solve the user SESSION expiration time? Remember that memcached’s add() method has an expiration time parameter $exp? Just set this parameter value to be less than the maximum survival time of SESSION. In addition, don’t forget to extend the SESSION duration for those users who are always online. This can be solved in the write() method. By judging the time, the database data will be updated if the conditions are met.

5. Related resources

  • memcached official website
  • PHP memcached client
  • Download memcached-client.php

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321121.htmlTechArticleXiao Lida (KrazyNio AT hotmail.com), 2006.04. 06, please indicate the source for reprinting 1. Introduction to memcached in many We will all hear the name memcached on various occasions, but many students have only heard of it...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!