Analysis of memcached

Source: Internet
Author: User

Let's take a look at some basic working mechanisms of memcached.

Application background:

The Web application saves data to a relational database. The application server retrieves records from the database and returns the results to the browser. If there is too much data, the database server load will be too large and will eventually become a machine. When some of the data meets the following conditions:
  • Frequently accessed by clients
  • Average update frequency
The high-performance distributed memory cache server memcached can be used to cache database query results (atomic operations) to reduce database access times and increase the speed of Dynamic Web applications. The workflow is as follows (Figure obtained online): communication method and operation instructions: you can connect to the memcached server through Telnet,
$ telnet localhost 11211

You can use the set and get methods to perform the most basic key-value pairs:

set foo 0 0 3barSTOREDget fooVALUE foo 0 3barEND

Command format for data storage:

command <key> <flags> <expiration time> <bytes><value>

Parameters Usage
Key Key is used to find the cache value. foo is used in this article.
Flags It can include an integer parameter of a key-value pair. The client uses it to store additional information about the key-value pair.
Expiration time The duration of saving the key-value pair in the cache (in seconds, 0 indicates permanent). This article uses 0. You want to keep it until you manually delete it.
Bytes Byte points stored in the cache
Value Stored value (always in the second row), set as bar in this article

If you usesetThe command correctly sets the key-value pair, and the server uses the wordStored.

Other commands are similar:

  • Add: only when no key exists in the cache,addCommand to add a key-value pair to the cache. If a key already exists in the cache, the previous values remain the same and you will get a responseNot_stored.
  • Replace: only when the key already exists,replaceCommand to replace the key in the cache. If no key exists in the cache, you will receiveNot_storedResponse.
  • Get: used to retrieve values related to previously added key-value pairs. You will usegetPerform most search operations.
  • Delete: delete any existing values in memcached. You will use a key to calldeleteIf the key exists in the cache, the value is deleted. If it does not exist, returnNot_foundMessage.
  • Gets: functions are similar to basicgetCommand. The difference between the two commands is,getsThe returned information is slightly more: the 64-bit integer value is very similar to the "version" identifier of the name/value pair.
  • CAS: (check and set) is a very convenient memcached command used to set the value of the name/value pair (if this name/value pair is executed on your lastgets). It usessetSyntax similar to the command, but includes an additional value:getsThe returned additional value.

The function of BTW and CAS is similar to that of updating files in CVS file version control. After obtaining the latest update information, you must know the latest flag and update it again, which is very useful.

Two memcached commands are used to monitor and clear memcached instances. They arestatsAndflush_allCommand.

Stats is used to list the storage status of servers, and flush_all is used to clear all key-value pairs.

The above is the basic operation. Next we will talk about how to use memcached on PHP.

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

First, PHP has a memcached extension. 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.

<? PHP header ("Content-Type: text/html; charset = UTF-8"); require_once ("memcached-client.php"); $ Options = array ('servers' => array ('123. 0.0.1: 11211 '), // address and port of the memcached service. Multiple array elements can be used to indicate multiple memcached services 'debug' => false, // whether to enable debug to print the debug string 'compress _ threshold '=> 10240, // how many bytes are compressed to 'persistant' => false // whether to use persistent connections ); $ MC = new memcached ($ options); $ key = 'a'; flush_all ($ options); $ Mc-> Add ($ key, 'kjohn '); // $ Mc-> Replace ($ key, "Mike"); $ val = $ Mc-> get ($ key); echo $ val; function flush_all ($ options) {list ($ host, $ port) = explode (":", $ options ["servers"] [0]); $ cmd = "flush_all \ n"; $ timeout = 0.25; $ socket = @ fsockopen ($ host, $ port, $ errno, $ errstr, $ timeout ); // do not buffer writes stream_set_write_buffer ($ socket, 0); fwrite ($ socket, $ cmd, strlen ($ cmd )); // $ res = trim (fgets ($ socket); // echo "$ res! ";}?

On memcached-client.php usage, there are a lot of online, but also very simple, here is not much to introduce.

Because the clearing command cannot be found in the memcached-client, the run_command ($ sock, $ cmd) method provided by memcached is also used on the Internet, after carefully analyzing the source code of PHP-memcached-client, we found that,

Execute flush_all on memcache. You can use fsockopen to customize a socket to write "flush_all \ n" to clear key-value pairs.

For some operations with data returned, you can use fgets ($ socket) to obtain the returned information.

BTW, you can extend this function to the source code of PHP-memcached-client.

In practical applications, the database query result set is usually saved to memcached. The result set is directly obtained 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.

<? 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);?>

 

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.