Home  >  Article  >  Backend Development  >  Memcache introductory tutorial Memcache php caching technology_PHP tutorial

Memcache introductory tutorial Memcache php caching technology_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:07:41688browse

What is Memcache
Memcache is a project of danga.com. It was first used to serve LiveJournal. Currently, many people around the world use this caching project to build their own large-load websites to share the pressure of database tutorials.
It can handle any number of connections and uses non-blocking network IO. Since its working mechanism is to open up a space in the memory and then create a HashTable, Memcached manages these HashTables by itself.
Memcache official website: http://www.danga.com/memcached. For more detailed information, you can come here to learn

Why are there two names: Memcache and memcached?
Actually, Memcache is the name of this project, and memcached is the name of its main program file on the server side. You know what I mean~~~~. One is the project name, and the other is the main program file name. I saw many people on the Internet who didn’t understand, so they used them interchangeably.

Memcache installation
is divided into two processes: memcache server installation and memcached client installation.
The so-called server-side installation is to install Memcache on the server (usually a Linux system) to store data
The so-called client-side installation refers to the PHP tutorial (or other programs, Memcache also has other good API interfaces) To use the functions provided by Memcache on the server side, you need to add extensions to PHP.

PHP’s Memcache

Copy the code as follows:
< ?php
//Connection

$mem = new Memcache;
$mem ->connect("192.168.0.200", 12000);

//Save data

$mem->set('key1', 'This is first value', 0, 60);
$val = $mem->get('key1');
echo "Get key1 value: " . $val ."
";

//Replace data

$mem->replace('key1', 'This is replace value', 0, 60);
$val = $mem->get('key1') ;
echo "Get key1 value: " . $val . "
";

//Save the array

$arr = array('aaa', ' bbb', 'ccc', 'ddd');
$mem->set('key2', $arr, 0, 60);
$val2 = $mem->get('key2' );
echo "Get key2 value: ";
print_r($val2);
echo "
";

//Delete data

$mem->delete('key1');
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "
";

//Clear all data

$mem->flush();
$val2 = $mem->get('key2');
echo "Get key2 value: ";
print_r($val2);
echo "
";

//Close the connection
$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

Initialize a Memcache object:

$mem = new Memcache;

Connect to our Memcache server, first The first parameter is the IP address of the server, which can also be the host name. 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 key of the data, used to locate a data. The second parameter is the content of the data that needs to be saved. Here is a string. The third parameter is a mark. , generally set to 0 or MEMCACHE_COMPRESSED. The fourth parameter is the validity period of the data, which means that the data is valid within this time. If this time passes, the data will be cleared by the Memcache server. The unit is seconds. If set to 0, it will be valid forever. We set 60 here, which is valid for one minute:
$mem->set('key1', 'This is first value', 0, 60);

Get a piece of data from the Memcache server. It has only one parameter, which is the key to get the data. Here is the key1 set in the previous step. Now after getting this data, output the output:

$val = $mem->get('key1′);
echo "Get key1 value: " . $val;

Now use the replace method to replace the value of key1 above. The parameters of the replace method are as follows set is the same, but the first parameter key1 must be the key to replace the data content. The final output is:

$mem->replace('key1′, 'This is replace value', 0 , 60);
$val = $mem->get('key1′);
echo "Get key1 value: " . $val;

Similarly, Memcache can also save arrays Yes, the following is to save an array on Memcache, then get it back and output it

$arr = array('aaa', 'bbb', 'ccc', 'ddd');
$mem->set('key2′, $arr, 0, 60);
$val2 = $mem->get('key2′);
print_r($val2);

Now delete a data, use the delte interface, the parameter is a key, and then you can put the Memcache server The data of this key is deleted, and there is no result in the final output

$mem->delete('key1′);
$val = $mem->get('key1′);
echo "Get key1 value: " . $val . "
";

Finally, we clear all the data saved on the Memcache server, and we will find that the data is gone, and finally output key2 The data is empty, and finally the connection is closed

$mem->flush();
$val2 = $mem->get('key2′);
echo "Get key2 value: ";
print_r($val2);
echo "
";

Use of Memcache
Websites that use Memcache generally have relatively large traffic. In order to alleviate the problem of database Pressure, let Memcache serve as a cache area to save part of the information in the memory, so that it can be accessed quickly on the front end. So the general focus is on how to share database pressure and distribute it. After all, the memory capacity of a single Memcache is limited. I simply put forward my personal opinions here. I have not practiced them and should only be used as a reference.

Distributed application
Memcache originally supports distributed, but our client has been slightly modified to provide better support. Our keys can be encapsulated appropriately and regularly. For example, for a user-based website, each user has a User ID, so it can be extracted and accessed according to a fixed ID. For example, users starting with 1 are stored in the first On one Memcache server, the data of users starting with 2 is stored on the second Memcache server. The access data is first converted and accessed according to the User ID.

But this has the disadvantage that you need to judge the User ID. If the business is inconsistent, or other types of applications may not be so suitable, you can consider it based on your actual business, or think about something more suitable. method.

Reduce database pressure
This is quite important. All data are basically stored in the database. Frequent access to the database each time results in a huge decline in database performance and the inability to service updates at the same time. Many users, such as MySQL, lock tables very frequently, so let Memcache share the pressure on the database. We need a way to change the current architecture in a way that is relatively small and does not require large-scale changes to the front end.

A simple method I am considering:
The back-end database operation module extracts all Select operations (regardless of update/delete/insert), and then calculates the corresponding hash algorithm on the corresponding SQL Get a hash data key (such as MD5 or SHA), and then use this key to find the data in Memcache. If the data does not exist, it means that it has not been written to the cache, then extract the data from the database. One is an array class. format, and then set the data into Memcache. The key is the hash value of this SQL, and then set an expiration time accordingly, such as one hour. Then the data in one hour will be extracted from the cache, effectively reducing the pressure on the database. . The disadvantage is that the data is not real-time. When the data is modified, it cannot be displayed on the front end in real time, and it may also occupy a large amount of memory. After all, the amount of data selected each time may be huge. This is a factor that needs to be considered.

Security of Memcache
Our above Memcache server is directly connected through the client and operates directly without any verification process. In this way, if the server is directly exposed to the Internet, it is more dangerous and light. Then the data leakage is viewed by other unrelated people, or worse, the server is invaded, because Mecache is running with root privileges, and there may be some unknown bugs or buffer overflows in it. These are unknown to us, so they are dangerous. Sex is predictable. For the sake of security, I would like to make two suggestions to prevent hacker intrusion or data leakage.

Intranet access
It is best to use intranet access between two servers, usually between the Web server and the Memcache server. Common servers have two network cards, one pointing to the Internet and one pointing to the intranet. Then let the web server access the Memcache server through the intranet network card. When our Memcache server is started, it monitors the IP address and IP address of the intranet. Ports and intranet access can effectively prevent other illegal access.
# memcached -d -m 1024 -u root -l 192.168.0.200 -p 11211 -c 1024 -P /tmp/memcached.pid
The Memcache server is set to monitor the IP of 192.168.0.200 through the intranet Port 11211, occupies 1024MB of memory, and allows a maximum of 1024 concurrent connections

Set up a firewall
A firewall is a simple and effective way. If both servers are connected to the Internet and you need to access Memcache through the external IP, you can consider using a firewall or proxy program to filter out illegal access.
Generally, under Linux, we can use iptables or ipfw under FreeBSD to specify some rules to prevent some illegal access. For example, we can set up to 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 above iptables rule only allows the 192.168.0.2 web server to access the Memcache server, which can effectively prevent some illegal access. Correspondingly, you can also add some other rules to enhance security. This can be done according to your own needs.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444929.htmlTechArticleWhat is Memcache? Memcache is a project of danga.com. It was first used to serve LiveJournal and is currently used by many around the world. People use this caching project to build their own high-load websites to split...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn