PHP + memcached Cache Technology instance

Source: Internet
Author: User
Tags php memcached

1. Introduction to memcached

On many occasions, we will hear the name memcached, but many of you have heard of it, and have never used it or actually understood it. I only know that it is a good stuff. Memcached is an efficient and fast distributed memory object cache system, mainly used to accelerate Dynamic WEB applications.

Ii. 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 uses libevent. What I downloaded is

Next are the libevent-1.1a.tar.gz and memcached-1.1.12.tar.gz unwrapped packages, compilation, installation:

# Tar-xzf libevent-1.1a.tar.gz # cd libevent-1.1a #. /configure -- prefix =/usr # make install # cd .. # tar-xzf memcached-1.1.12.tar.gz # cd memcached-1.1.12 #. /configure -- prefix =/usr # make install

After the installation is complete, memcached should be in/usr/bin/memcached.

Iii. Run the memcached daemon

Running the memcached daemon is simple. You only need one command line and no configuration file needs to be modified.

/Usr/bin/memcached-d-m 128-l 11211-u httpd

Parameter description:

-D runs memcached in daemon mode;-m sets the memory size available for memcached, in MB;-l sets the IP address of the listener, if it is a local machine, this parameter can be left unspecified.-p is used to set the listening port. The default value is 11211, so this parameter can be left unspecified.-u specifies the user. If the current value is root, you need to 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. How memcached works

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. 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.

Iii. How does PHP act as the memcached client?

You can use PHP as the memcached client to call the memcached service for object access.

First, PHP has an extension called memcache, which must be included during compilation in Linux.-Enable-memcache [= dir]Option, Window
In php. ini, remove the comments from the front of php_memcache.dll 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.

Iv. php memcached application example

First download the memcached-client.php, after downloading the memcached-client.php, You can through this file class "memcached" on memcached
The service has been operated. In fact, code calls are very simple. The main methods used include 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)
Replace $ value with the content of the $ key object 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:

<? PHP
// 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 ):

<? Php
$ SQL = 'select * FROM users ';
$ Key = md5 ($ SQL); // memcached object identifier
If (! ($ Datas = $ mc-> get ($ key ))){
// 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 );
} Else {
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 operation ends (or session_write_close () is used), my_sess: Write () is called () method to write data to the database. In this way, database operations are still performed each time. optimization is also required for this method. Use a global variable to record
Session data, and then compare the data in the write () method to whether the data is the same as the session data to be written. The database is connected and written to the database, and the corresponding objects in memcached are deleted, if the session data is the same, it indicates that the session data has not changed, so you can directly return the data without any operation. How can you solve the problem of 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 online users.
Solve the problem in the write () method. By determining the time, the database data is updated if the condition is met.

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: 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.