Memcache is a project of danga.com. It was first served for LiveJournal. Currently, many people around the world use this cache Project to build your own heavy-load website to share the pressure on the database. 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, more detailed information can be found here.
Why are there two names: Memcache and memcached? In fact, 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
It 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 installation refers to PHP (or other programs, Memcache also has other good api interfaces provided) to use the functions provided by Memcache on the server side, which requires PHP to add extensions.
PHP’s Memcache
<?php //连接 $mem = new Memcache; $mem->connect("db.nowamagic.net", ); //保存数据 $mem->set('key', 'This is first value', , ); $val = $mem->get('key'); echo "Get key value: " . $val ."<br />"; //替换数据 $mem->replace('key', 'This is replace value', , ); $val = $mem->get('key'); echo "Get key value: " . $val . "<br />"; //保存数组 $arr = array('aaa', 'bbb', 'ccc', 'ddd'); $mem->set('key', $arr, , ); $val = $mem->get('key'); echo "Get key value: "; print_r($val); echo "<br />"; //删除数据 $mem->delete('key'); $val = $mem->get('key'); echo "Get key value: " . $val . "<br />"; //清除所有数据 $mem->flush(); $val = $mem->get('key'); echo "Get key value: "; print_r($val); echo "<br />"; //关闭连接 $mem->close(); ?>
If normal, the browser will output:
Get key value: This is first value
Get key value: This is replace value
Get key value: Array ( [] => aaa [] => bbb [] => ccc [] => ddd )
Get key value:
Get key value:
Program code analysis
Initialize a Memcache object: $mem = new Memcache;
Connect to our Memcache server. 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('key′); echo "Get key value: " . $val;
Now use the replace method to replace the value of key1 above. The parameters of the replace method are the same as set, but the first parameter key1 must be the key to replace the data content. The final output is:
$mem->replace('key', 'This is replace value', , ); $val = $mem->get('key'); echo "Get key value: " . $val;
Similarly, Memcache can also save arrays. The following is an array saved in Memcache, then retrieved and output:
$arr = array('aaa', 'bbb', 'ccc', 'ddd'); $mem->set('key', $arr, , ); $val = $mem->get('key'); print_r($val);
Now delete a piece of data, use the delte interface, the parameter is a key, and then you can delete the data of the key in the Memcache server. There is no result in the final output:
$mem->delete('key'); $val = $mem->get('key'); echo "Get key value: " . $val . "<br />";
Finally, we clear all the data saved on the Memcache server. We will find that the data is gone. The final output key2 data is empty, and finally the connection is closed:
$mem->flush(); $val = $mem->get('key'); echo "Get key value: "; print_r($val); echo "<br />";
Using Memcache
Websites that use Memcache generally have relatively large traffic. In order to relieve the pressure on the database, Memcache is used as a cache area to save part of the information in the memory, so that it can be accessed quickly on the front end. Then 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 Applications
Memcache originally supports distributed distribution, 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.
However, this has the disadvantage that it requires judgment on the User ID. If the business is inconsistent, or other types of applications may not be so suitable, then you can consider it based on your actual business, or think of a more suitable method.
Reduce database pressure
This is quite important. All data is basically stored in the database. Frequent access to the database each time leads to a severe decline in database performance and the inability to serve more users at the same time. For example, MySQL is particularly frequent. lock table, then 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 considered:
The back-end database operation module extracts all Select operations (regardless of update/delete/insert), and then performs the corresponding hash algorithm on the corresponding SQL to calculate a hash data key (such as MD5 or SHA), and then Search the data for this key 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 in an array format, and then set the data to Memcache. The key is this SQL hash value, 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.
Memcache security
Our above Memcache server is operated directly through the client connection without any verification process. If the server is directly exposed to the Internet, it is more dangerous. At least the data will be leaked and viewed by other unrelated people. More seriously, the server is invaded because Mecache runs with root privileges, and there may be some unknown bugs or buffer overflows in it. These are unknown to us, so the danger is foreseeable. 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 make the access between the two servers in the form of an intranet, 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 listen to the 11211 port of the 192.168.0.200 IP on the intranet, occupying 1024MB of memory, and allowing a maximum of 1024 concurrent connections.
Set up firewall
Firewall is a simple and effective method. If both servers are connected to the Internet and you need to access Memcache through external IP, you can consider using a firewall or proxy program to filter 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 ... –dport -j ACCEPT
# iptables -A INPUT -p udp -s ... –dport -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 based on your own Need to be done.