PHP Memory Cache Acceleration memcached installation and usage

Source: Internet
Author: User
Tags php memcached
Memcached is a good introduction to memcached in many occasions, but many of you have heard of it and never used it or actually understood it. Here is a brief introduction. 1. Introduction to memcached in many occasions, we will hear the name of memcached, but many people have heard it, but they have never used it or actually learned it. they only know it is a good stuff. Memcached is an efficient and fast distributed memory object cache system, mainly used to accelerate dynamic WEB applications. 2. install memcached first download memcached, the latest version is 1.1.12, directly from the official website to download to the memcached-1.1.12.tar.gz. In addition, memcached used libevent and I downloaded the libevent-1.1a.tar.gz. Next is to unwrap the libevent-1.1a.tar.gz and memcached-1.1.12.tar.gz, compile, install: # 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. 3. run the memcached daemon to run the memcached daemon. you only need to run the memcached daemon with one command line. you do not need to modify any configuration file (or modify the configuration file ): /usr/bin/memcached-d-m 128-l 192.168.1.1-p 11211-u httpd parameter explanation:-d runs memcached in daemon mode;
-M: Set the memory size available for memcached, in MB;
-L set the IP address of the listener. if it is a local machine, this parameter is usually not set;
-P: Set the listening port. the default value is 11211. Therefore, you can leave this parameter unspecified;
-U specifies the user. if the current user is root, you must use this parameter to specify the user. Of course, there are other parameters that can be used. man memcached can be seen at a moment. IV. working principle of memcached first, memcached runs on one or more servers as a daemon and 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 #, and C. After the PHP client establishes a connection with the memcached service, the next thing is to access the object. each accessed object has a unique identifier key, and the access operation is performed through this key, objects saved to memcached are actually stored in the memory, not in the cache file. This is why memcached is so efficient and fast. Note that these objects are not persistent. after the service is stopped, the data in the objects will be lost. 3. PHP can be used as a memcached client in two ways to use PHP as a memcached client and call the memcached service for object access. First, PHP has an extension called memcache. during compilation in Linux, The-enable-memcache [= DIR] option must be included, and the Window is in php. remove the annotator in front of php_memcache.dll in ini to make it available. In addition, there is also a way to avoid the trouble of extension and re-compilation, that is, directly using php-memcached-client. The second method is used in this article. although the efficiency is slightly lower than that of the extended library, it is not a problem. 4. PHP memcached application example first download the memcached-client.php, after downloading the memcached-client.php, you can operate the memcached service through the class "memcached" in this file. In fact, code calls are very simple. The main methods used are add (), get (), replace (), and delete (). The methods are described as follows: add ($ key, $ val, $ exp = 0)
Write an object to memcached. $ key is the unique identifier of the object. $ val is the data of the written object. $ exp is the expiration time, in seconds. the default value is unlimited; get ($ key)
Get object data from memcached and get it through the unique identifier $ key of the object; replace ($ key, $ value, $ exp = 0)
Use $ value to replace the content of an object with $ key in memcached. the parameter works only when the $ key object exists like the add () method. delete ($ key, $ time = 0)
Delete an object with the identifier $ key in memcached. $ time is an optional parameter, indicating how long it will take before deletion. The following is a simple test code that allows you to access the object data with the identifier 'MyKey:

The code is as follows:


// Contains the memcached class file
Require_once ('memcached-client. php ');
// Option settings
$ Options = array (
'Servers' => array ('192. 168.1.1: 100'), // address and port of the memcached service. multiple array elements can be used to represent multiple memcached services.
'Debug' => true, // whether to enable debug
'Compress _ threshold '=> 10240, // when the number of bytes of data exceeds
'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 an object to memcached
$ Mc-> add ($ key, 'some random string ');
$ 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' => 'hahaha', '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 it very easy? in actual applications, the database query result set is usually saved to memcached. The result set is obtained directly from memcached during the next visit, instead of performing database query operations, this can greatly reduce the burden on the database. Generally, the value after the md5 () of the SQL statement is used as the unique identifier key. Below is an example of using memcached to cache the database query result set (this code snippet is followed by the above sample code ):

The code is as follows:


$ SQL = 'select * FROM users ';
$ Key = md5 ($ SQL); // memcached object identifier
{
// If no cached data is 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 the next access.
$ Mc-> add ($ key, $ datas );
{
Echo "n". str_pad ('read datas from memcached. ', 60,' _ '). "n ";
}
Var_dump ($ datas );
?>


It can be seen that after memcached is used, the database connection and query operations can be reduced, the database load is reduced, and the script running speed is also improved. I have previously written an article titled "PHP achieves multi-server sharing SESSION data". the SESSION in this article is saved in a database. when the concurrency traffic is high, the load on the server is very large and often exceeds the maximum number of connections in MySQL. using memcached, we can solve this problem well. The working principle is as follows:
When a user accesses the webpage, check whether the current user's SESSION data exists in memcached and use session_id () as the unique identifier. if the data exists, the system returns the result directly. if the data does not exist, the system connects to the database, obtain the SESSION data and save the data to memcached for the next use;
When the current PHP running ends (or session_write_close () is used), the My_Sess: write () method is called to write data to the database. in this way, database operations are still performed each 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 the data with the SESSION data to be written in the write () method, different databases are connected and written to the database. at the same time, the corresponding objects in memcached are deleted. if they are the same, the SESSION data is not changed, so no operation can be performed and the data is returned directly;
So how can we solve the user's SESSION expiration time? Do you remember that the add () method of memcached has an expiration time parameter $ exp? Set this parameter to a value smaller than the maximum SESSION survival time. In addition, do not forget to extend the SESSION duration for 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 are met.

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.