How to use Memcached in PHP

Source: Internet
Author: User
Memcached is a high-performance distributed memory cache server. The general purpose is to reduce the number of database accesses by caching database query results, so as to speed up dynamic Web applications and improve scalability. This article describes how to use Memcached in PHP. the code of a friend who is interested is 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;

The code is as follows:


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;

The code is as follows:


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 '); // Set the options to $ options = array ('servers' => array ('123. 168.1.1: 11211 '), // address and port of the memcached service. multiple array elements can be used to indicate multiple memcached services 'debug' => true, // whether to enable debug 'compress _ threshold '=> 10240, // compress 'persistant' => false // whether to use persistent connections when data exceeds the size of bytes ); // Create a memcached object instance $ mc = new memcached ($ options); // Set the unique identifier used by this script $ key = 'MyKey '; // write the object $ mc-> add ($ key, 'Some Random strings '); $ 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 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.

The above content is a small Editor to introduce how PHP uses Memcached. I hope it will help you!

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.