How PHP uses the memcached_php instance

Source: Internet
Author: User

Introduction of Memcached

Memcached is a high-performance distributed memory cache server. The purpose of the general use is to reduce the number of database visits by caching database query results to improve the speed and scalability of dynamic Web applications. It can handle any number of connections and use non-blocking network IO. Because its working mechanism is to open up a space in memory, and then establish a hashtable,memcached self management of these hashtable.

Second, memcached installation

The first is the 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 the libevent, I downloaded is the 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 separately:
# 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 configuration files to modify (and no configuration files to modify):
/usr/bin/memcached-d-M 128-l 192.168.1.1-p 11211-u httpd
Parameter explanation:

-D to run the Memcached;-m setting in a daemon (daemon) memcached The amount of memory that can be used, in units of M-L, to set the IP address that is listening, and, if this is the case, you can usually not set this parameter;-P set the listening port, default to 11211, so You can specify the user without setting this parameter,--------if the current is root, you need to use this parameter to specify the user.

Of course, there are other parameters can be used, man memcached can be seen.

Iv. the working principle of memcached

First, memcached is run in a daemon to one or more servers, ready to accept client connection operations, clients can be written in a variety of languages, currently known client APIs including PERL/PHP/PYTHON/RUBY/JAVA/C#/C, and so on. PHP and other clients in connection with the Memcached service, the next thing is to access objects, each accessed object has a unique identifier key, access operations through this key, saved to the Memcached object is actually placed in memory, is not stored 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 will be lost after the service is stopped.

V. How PHP as a memcached client

There are two ways to make PHP a memcached client, invoking Memcached services for object access.

First, PHP has an extension called memcache, Linux needs to be compiled with the –enable-memcache[=dir] option, Window under the php.ini to remove Php_memcache.dll the front of the annotation to make it available.

In addition, there is a way to avoid the expansion, recompilation of the trouble, that is, the direct use of php-memcached-client.

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

Six, 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 described below:

Copy Code code as follows:

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

Writes an object to the memcached, $key is the object's unique identifier, $val is the object data written, $exp is the expiration time, the unit is seconds, and the default is unlimited time;

Get ($key)

Obtaining the object data from the memcached, $key obtaining by the unique identifier of the object;

Copy Code code as follows:

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

Use $value to replace the contents of an object in the memcached with the $key identifier, which, like the Add () method, works only if the $key object exists;

Copy Code code as follows:

Delete ($key, $time = 0)

Deletes an object in the memcached that has an identifier of $key, $time an optional parameter, indicating how long it will take to wait before the deletion.

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

 <?php//contains memcached class file require_once (' memcached-client.php ');//Option setting $options = Arr  Ay (' Servers ' => array (' 192.168.1.1:11211 '),//memcached service address, port, multiple array elements can be used to represent multiple memcached service ' debug ' => true,//Open
Debug ' compress_threshold ' => 10240,//More than the number of bytes of data compressed ' persistant ' => false//whether using a persistent connection);
Create a Memcached object instance $MC = new memcached ($options);
Sets the unique identifier used by this script $key = ' MyKey ';
Write objects to the memcached $mc->add ($key, ' some random strings ');
$val = $MC->get ($key); echo "n". Str_pad (' $MC->add () ', 60, ' _ '). "
n ";
Var_dump ($val);
Replaces the object data value that has been written $MC->replace ($key, Array (' some ' => ' haha ', ' array ' => ' xxx '));
$val = $MC->get ($key); echo "n". Str_pad (' $MC->replace () ', 60, ' _ '). "
n ";
Var_dump ($val);
Deletes the object in the memcached $mc->delete ($key);
$val = $MC->get ($key); echo "n". Str_pad (' $MC->delete () ', 60, ' _ '). "
n "; Var_dump ($val);?> 

is not very simple, in practical applications, the result set of the database query is usually saved to the memcached, the next visit directly from the memcached, and no longer do the database query operations, which can greatly reduce the burden of the database. The value after the SQL statement MD5 () is typically used as the unique identifier key. Below is an example of caching a database query result set using memcached (this code fragment immediately follows the example code above):

<?php
$sql = ' SELECT * from users ';
$key = MD5 ($sql); Memcached Object identifier
if (!) ( $datas = $MC->get ($key))) {
//cache data is not obtained in memcached, then a database query is used to get the recordset.
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;
Saves the result set data obtained in the database to memcached for use on the next visit.
$MC->add ($key, $datas);
else {
echo "n". Str_pad (' Read datas from memcached. ', 60, ' _ '). " n ";
}
Var_dump ($datas);

It can be seen that the use of memcached, you can reduce the database connection, query operations, the database load down, the speed of the script also improved.

I have previously written a "PHP implementation of multiple server sharing session data" article, the text of the session is used to save the database, in the concurrent access to large, the server load will be very large, often exceeding the maximum number of MySQL connections, using memcached, We can solve this problem very well, the working principle is as follows:

When the user accesses the Web page, see if there is a session data for the current user in the memcached, use session_id () as the unique identifier, or if the data exists, return 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, when the current PHP run ends (or uses session_write_close ()), the My_sess::write () method is invoked to write the data to the database, so that every time there is a database operation, for this method , and it needs to be optimized. Use a global variable to record the session data when the user enters the page, and then compare the data in the write () method with the same session data that you want to write, to make a database connection, write to the database, and delete the corresponding object in the memcached. If the same, the session data does not change, so you can do nothing, directly returned, then the user session expiration time how to solve? Remember the memcached Add () method has an expiration time parameter $exp? The parameter value is set to less than the session maximum survival time. And don't forget to give those who have been online the duration of the session, which can be resolved in the Write () method, and the database data is updated by judging the time and complying with the criteria.

The above content is small make up to everybody introduce PHP how to use memcached, hope to help everybody!

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.