PHP Memory Cache acceleration feature memcached installation and usage _php tutorial

Source: Internet
Author: User
Tags php memcached
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 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 is the first download memcached, the current 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. Next is the libevent-1.1a.tar.gz and memcached-1.1.12.tar.gz unpacked, compiled, installed: # 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
# when the make install is complete, memcached should be in/usr/bin/memcached. Third, running the memcached daemon running the memcached daemon is very simple, just a command line, no need to modify any configuration file (there is no configuration file for you to modify):/usr/bin/memcached-d-M 128-l 192.168.1.1- P 11211-u httpd parameter explanation:-D runs the memcached in the Daemon (daemon) mode;
-M sets the amount of memory that memcached can use, in units of M;
-L Set the listening IP address, if it is native, it is usually possible not to set this parameter;
-P Sets the listening port, which defaults to 11211, so you can also not set this parameter;
-u specifies that the user should be specified using this parameter if it is currently root. Of course, there are other parameters to use, man memcached can be seen. Iv. working principle of memcached first, the memcached is run in a daemon mode in one or more servers, at any time to accept client connection operation, 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. Third, how PHP as a memcached client there are two ways to make PHP as a memcached client, call Memcached Service for object access operations. First, PHP has an extension called memcache, which needs to be compiled with the –enable-memcache[=dir] option under Linux, and Window will remove the annotation from the front of Php_memcache.dll in php.ini to make it usable. In addition, there is a way to avoid the problem of scaling and recompiling, which is to use php-memcached-client directly. This article chooses the second way, although the efficiency will be slightly worse than the expansion library, but the problem is not big. PHP memcached Application Example first download 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 way to use is 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 being written, $exp is the expiration time, in seconds, and the default is unlimited time; get ($key)
Gets the object data from the memcached, $key obtained by the unique identifier of the object; replace ($key, $value, $exp =0)
Use $value to replace object content with an identifier $key in memcached, which, like the Add () method, 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:
Copy CodeThe code is as follows:
Contains the 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,//compress more than a few bytes of data
' Persistant ' = false//whether to use persistent connection
);
Creating an Memcached object instance
$MC = new memcached ($options);
Sets the unique identifier used by this script
$key = ' MyKey ';
Writing 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);
Replace a 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 an object in memcached
$MC->delete ($key);
$val = $MC->get ($key);
echo "n". Str_pad (' $MC->delete () ', 60, ' _ '). " 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):
Copy CodeThe code is as follows:
$sql = ' SELECT * from users ';
$key = MD5 ($sql); Memcached Object identifiers
{
If the cached data is not obtained in memcached, the recordset is obtained 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;
Saves the result set data obtained in the database to memcached for use on the next visit.
$MC->add ($key, $datas);
{
echo "n". Str_pad (' Read datas from memcached. ', 60, ' _ '). " 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;
At the end of the current PHP run (or using Session_write_close ()), the My_sess::write () method is called and the data is written to the database, so there is still a database operation, which needs to be optimized for this method. 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, directly returned;
Then how to solve the user SESSION expiration time? 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/320520.html www.bkjia.com true http://www.bkjia.com/PHPjc/320520.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 ...

  • Related Article

    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.