Memcache Basic Tutorials

Source: Internet
Author: User

What is Memcache?
Memcache is a danga.com project, the first to serve LiveJournal, many people around the world use this cache project to build their own heavy load of the site, to share the pressure of the database.
It can handle any number of connections, using non-blocking network IO. Because it works by opening up a space in memory, it then builds a hashtable,memcached self-managing these hashtable.
Memcache Official website: http://www.danga.com/memcached, more detailed information can come here to understand:)

Why are there two names of Memcache and memcached?
In fact Memcache is the name of this project, and memcached is its server side of the main program file name, know what I mean to put ~ ~ ~ ~ ~. One is the project name, one is the main program file name, on the internet to see a lot of people do not understand, so mixed.

Installation of Memcache
It is divided into two processes: Memcache server-side installation and memcached client installation.
The so-called server-side installation is to install Memcache on the server (generally Linux system) to implement data storage
The so-called client installation refers to PHP (or other programs, memcache and other good API interface) to use the server-side memcache provided functions, PHP needs to add extensions.

We can refer to the specific configuration:
Memcache installation under Linux: http://www.ccvita.com/257.html
Memcache installation under Windows: http://www.ccvita.com/258.html
Memcache Basic Tutorial: http://www.ccvita.com/259.html
Discuz! 's memcache cache implementation: http://www.ccvita.com/261.html
Memcache Agreement Chinese version: http://www.ccvita.com/306.html
Memcache Distributed Deployment scenario: http://www.ccvita.com/395.html

PHP's Memcache

1<?PHP2 //Connection3 $mem=NewMemcache;4 $mem->connect ("192.168.0.200", 12000);5 6 //Save Data7 $mem->set (' Key1 ', ' This is first value ', 0, 60);8 $val=$mem->get (' Key1 ');9 Echo"Get Key1 Value:".$val." <br/> ";Ten  One //Replace Data A $mem->replace (' Key1 ', ' This is replace value ', 0, 60); - $val=$mem->get (' Key1 '); - Echo"Get Key1 Value:".$val. "<br/>"; the  - //Save Array - $arr=Array(' AAA ', ' BBB ', ' CCC ', ' DDD ')); - $mem->set (' Key2 ',$arr, 0, 60); + $val 2=$mem->get (' Key2 '); - Echo"Get Key2 Value:"; + Print_r($val 2); A Echo"<br/>"; at  - //Delete Data - $mem->delete (' Key1 '); - $val=$mem->get (' Key1 '); - Echo"Get Key1 Value:".$val. "<br/>"; -  in //Clear All data - $mem-Flush(); to $val 2=$mem->get (' Key2 '); + Echo"Get Key2 Value:"; - Print_r($val 2); the Echo"<br/>"; *  $ //Close ConnectionPanax Notoginseng $mem-close (); -?>

If normal, the browser will output:
Get key1 Value:this is first value
Get key1 Value:this is replace value
Get key2 Value:array ([0] = AAA [1] = BBB [2] = CCC [3] = = DDD)
Get Key1 Value:
Get Key2 Value:

Program Code Analysis

Initializes an Memcache object:
$mem = new Memcache;

Connect to our Memcache server, the first parameter is the IP address of the server, the host name, and the second parameter is the open port of Memcache:
$mem, connect ("192.168.0.200", 12000);

Save a data to the Memcache server, the first parameter is the data key, used to locate a data, the second parameter is to save the data content, here is a string, the third parameter is a marker, generally set to 0 or memcache_compressed on the line, The fourth parameter is the validity period of the data, that is, the data in this time is valid, if the past this time, then the memcache server side will be purged of this data, the unit is seconds, if set to 0, it is always valid, we set up here 60, is a minute effective time:
$mem->set (' key1', ' This is first value ', 0, );

Get a piece of data from the Memcache server, it has only one parameter, is the key that needs to get the data, we here is the key1 that the previous step sets, now obtains this data after output:
$val = $mem->get ('key1 ');
echo "Get key1 value:" . $val;

Instead of replacing the value of the above key1 with the Replace method, the Replace method parameter is the same as set, but the first parameter, Key1, must be the key to replace the data content, and the final output is:
$mem->replace (' Key1 ', ' This is replace value ', 0;
$val = $mem->get (' key1 ');
echo "Get key1 Value: ". $val;

Similarly, memcache can also save an array, the following is an array saved on memcache, and then get back and output
$arr  = Array ( ' AAA ',     ' CCC ' ,  );
$mem ->set ( ' Key2 ' ,   $arr ,  0 ,  60 );
$val 2  =  $mem ->get ( Span style= "color: #339966;" > ' Key2 ' );
Print_r ( $val 2 );

Now delete a data, using the Delte interface, the parameter is a key, and then be able to memcache server This key data delete, the last output when there is no result
$ mem ->delete ( ' Key1 ' );
$val  = $mem ->get ( ' key1 ' );
echo "get key1 value:  ". $val  . 

Finally, we put all the data stored on the Memcache server erased, we will find that the data is not, the final output key2 data is empty, and finally close the connection
$ mem->flush ();
$Val2 = $mem->get (' Key2 ');
echo "Get key2 value: ";
Print_r ($val 2);
echo "<br>";

Use of Memcache
The use of Memcache website general traffic is relatively large, in order to alleviate the pressure of the database, let Memcache as a cache area, the part of the information stored in memory, in the front-end can be quickly accessed. Then the general focus is to focus on how to share the database pressure and distributed, after all, the memory capacity of a single memcache limited. Here I briefly put forward my personal views, without practice, right when reference.

Distributed applications
Memcache originally support distributed, our client a little transformation, better support. Our key can be appropriately in a regular package, such as the user-oriented site, each users have a customer ID, you can follow a fixed ID to extract and access, such as 1, the beginning of the user is saved on the first memcache server, Data for users starting with 2 are saved on the second Mecache server, and access data is converted and accessed according to the user ID first.

However, this has the disadvantage that the user ID needs to be judged, if the business is inconsistent, or other types of applications may not be appropriate, then according to their actual business to consider, or to think of a more appropriate method.

Reduce database pressure
This is more important, all the data is basically stored in the database, every time the database is frequently accessed, resulting in a very slow database performance, can not serve more users at the same time, such as MySQL, especially frequent lock table, then let memcache to share the pressure of the database. We need to change the current architecture in a way that is small and does not change the front-end on a large scale.

An easy way for me to consider:
Back end of the database operation module, all the select operation is extracted (Update/delete/insert no matter), and then the corresponding SQL for the corresponding hash algorithm to calculate a hash data key (such as MD5 or SHA), Then the key to Memcache to find the data, if the data does not exist, the description has not been written to the cache, then extract the data from the database, an array class format, and then the data in set to Memcache, key is the SQL hash value, Then the corresponding setting of a failure time, such as one hours, then one hours of data are extracted from the cache, effectively reduce the pressure of the database. The disadvantage is that the data is not real-time, when the data has been modified, can not be real-time to the front-end display, and there may be a large memory footprint, after all, the number of select out of the data may be relatively large, this is a factor to consider.

Memcache's Safety
Our above Memcache server is directly through the client connection after direct operation, there is no verification process, so if the server is directly exposed to the Internet is more dangerous, light data leakage by other unrelated personnel view, heavy server was compromised, Because the Mecache is run as root, and there may be some of our unknown bugs or buffer overflow situation, these are unknown to us, so the danger is predictable. For the sake of safety, I do two suggestions, can be a little to prevent hacking or data leakage.

Intranet access
It is best to put the access between the two servers in the intranet form, usually between the Web server and the Memcache server. Universal servers are two network card, a point to the Internet, a point to the intranet, then let the Web server through the intranet network card to access the Memcache server, we memcache on the server when the boot on the network to listen to the IP address and port, Access between the intranet can effectively block other illegal access.
# memcached-d-M 1024-u root-l 192.168.0.200-p 11211-c 1024-p/tmp/memcached.pid
Memcache server-side setup listens on 11211 ports of 192.168.0.200 IP over the intranet, consumes 1024MB of memory, and allows up to 1024 concurrent connections

Set up a firewall
Firewall is a simple and effective way, if the two servers are hanging in the network, and need to access the Memcache through the extranet IP, then you can consider using a firewall or agent to filter illegal access.
Generally we can use iptables or FreeBSD under the Linux under the IPFW to specify some rules to prevent some illegal access, such as we can set only allow our Web server to access our Memcache server, while blocking other access.
# iptables-f
# iptables-p INPUT DROP
# iptables-a input-p tcp-s 192.168.0.2--dport 11211-j ACCEPT
# iptables-a input-p udp-s 192.168.0.2--dport 11211-j ACCEPT
The iptables rule above is to allow only 192.168.0.2 this Web server to the Memcache server access, can effectively prevent some illegal access, the corresponding can also add some other rules to enhance security, which can be done according to their own needs.

This article is collated and collected, the main source is: http://blog.csdn.net/heiyeshuwu/archive/2006/11/13/1380838.aspx

Memcache Basic Tutorials

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.