Php+memcached Caching Technology Example _php tutorial

Source: Internet
Author: User
Tags php memcached
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/memcached-d-M 128-l 192.168.1.1-p 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, manmemcached 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.

Iii. 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 , the Linux compiler need to take the –enable-memcache[=dir] option, Window under the php.ini to remove the Php_memcache.dll front of the note Release to make it available.

In addition, there is a way to avoid the problem of scaling and recompiling, which is to use php-memcached-clientdirectly.

This article chooses the second way, although the efficiency will be slightly worse than the expansion library, but the problem is not big.

Iv. 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 is described as follows:

Add ($key, $val, $exp = 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:


//contains memcached class file
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 multiple memcached services
' Debug '=true, //Whether to open debug
' Compress_threshold '=10240, compressed when//over how many bytes of data
' persistant '=false//Whether to use persistent connection
);
//Create Memcached object instance
$MC= newmemcached($options);
//Set the unique identifier used by this script
$key= ' MyKey ';
//Write an object to the memcached
$MC -Add($key, ' some random strings ');
$val= $MC -Get($key);
Echo"n".Str_pad(' $MC->add () ', -, '_')."n";
Var_dump($val);
//Replace a written object data value
$MC -Replace($key, Array (' some '=' haha ', ' array '=' xxx '));
$val= $MC -Get($key);
Echo"n".Str_pad(' $MC->replace () ', -, '_')."n";
Var_dump($val);
//delete objects in memcached
$MC -Delete($key);
$val= $MC -Get($key);
Echo"n".Str_pad(' $MC->delete () ', -, '_')."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):

$sql = ' SELECT * from users ';
$key= MD5($sql); //memcached Object Identifiers
if (! ($datas= $MC -Get($key)) ) {
//The cache data is not obtained in memcached, then the recordset is obtained using a database query.
Echo"n".Str_pad(' Read datas from MySQL. ', -, '_')."n";
$conn= mysql_connect(' localhost ', ' Test ', ' Test ');
mysql_select_db(' Test ');
$result= mysql_query($sql);
while ($row= Mysql_fetch_object($result))
$datas[] = $row;
//The result set data obtained in the database is saved to memcached for use on the next visit.
$MC -Add($key, $datas);
} else {
Echo"n".Str_pad(' Read datas from memcached. ', -, '_')."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

http://www.bkjia.com/PHPjc/478595.html www.bkjia.com true http://www.bkjia.com/PHPjc/478595.html techarticle memcached Introduction 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 ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.