What is memcache?
Memcache is a danga.com project that was first used for livejournal. Many people around the world use this cache project to build their own websites with high load to share the pressure on databases.
It can cope with any number of connections and use non-blocking network I/O. Because its working mechanism is to open up a space in the memory, and then create a hashtable, memcached self-manages these hashtable.
Official website of memcache: http://www.danga.com/memcached. For more detailed information, see here.
Why are there two memcache and memcached names?
In fact, memcache is the name of this project, and memcached is the master of its server.ProgramFile Name ~~~~. One is the project name, the other is the main program file name, and many people on the Internet do not understand it, so it is mixed.
Install memcache
There are two steps: Install the memcache server and the memcached client.
The so-called server-side installation is to install memcache on the server (generally Linux systems) to store data.
The so-called Client installation refers to PhP (or other programs, memcache and other good API interfaces) to use the functions provided by memcache on the server side. php needs to add extensions.
PHP memcache
CopyCode The Code is 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. "<br/> ";
// Replace Data
$ Mem-> Replace ('key1', 'this is replace value', 0, 60 );
$ Val = $ mem-> get ('key1 ');
Echo "Get key1 value:". $ Val. "<br/> ";
// 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 "<br/> ";
// Delete data
$ Mem-> Delete ('key1 ');
$ Val = $ mem-> get ('key1 ');
Echo "Get key1 value:". $ Val. "<br/> ";
// Clear all data
$ Mem-> flush ();
$ Val2 = $ mem-> get ('key2 ');
Echo "Get key2 value :";
Print_r ($ val2 );
Echo "<br/> ";
// Close the connection
$ Mem-> close ();
?>
If it is 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. The first parameter is the Server IP address or 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 the data content to be saved. Here is a string, the third parameter is a tag, which is usually set to 0 or memcache_compressed. The fourth parameter is the data validity period, which means that the data is valid during this time, the data will be cleared by the memcache server in seconds. If it is set to 0, it will always be valid. Here we set 60, which is the one-minute validity period:
$ Mem-> set ('key1', 'this is first value', 0, 60 );
Get a piece of data from the memcache server. It has only one parameter, that is, the key to get the data. Here is the key1 set in the previous step. Now we get the data and output it:
$ Val = $ mem-> get ('key1 ′);
Echo "Get key1 value:". $ val;
The replace method is used to replace the above key1 value. The parameters of the replace method are the same as those of the set method. However, the first parameter key1 must be the key to replace the data content, the output is as follows:
$ Mem-> Replace ('key1', 'this is replace value', 0, 60 );
$ Val = $ mem-> get ('key1 ′);
Echo "Get key1 value:". $ val;
Similarly, memcache can store arrays. Below is an array saved on memcache, which is then retrieved and output.
$ Arr = array ('aaa', 'bbb ', 'ccc', 'ddd ');
$ Mem-> set ('key2', $ arr, 0, 60 );
$ Val2 = $ mem-> get ('key2 ′);
Print_r ($ val2 );
Now, you can delete a data file by using the delte interface. The parameter is a key, and then you can delete the data of the key of the memcache server. No result is returned when the output is complete.
$ Mem-> Delete ('key1 ′);
$ Val = $ mem-> get ('key1 ′);
Echo "Get key1 value:". $ Val. "<br> ";
Finally, we clear all the data stored on the memcache server, and we will find that no data exists. Finally, the output key2 data is empty, and the connection is closed.
$ Mem-> flush ();
$ Val2 = $ mem-> get ('key2 ′);
Echo "Get key2 value :";
Print_r ($ val2 );
Echo "<br> ";
Use of memcache
Memcache websites generally have a large traffic volume. To relieve the pressure on the database, apsaradb for memcache is used as a cache area and some information is stored in the memory, allowing quick access at the front end. The general focus is to focus on how to share the pressure on the database and distribute it. After all, the memory capacity of a single memcache is limited. I would like to put forward my personal opinion here. Without practice, you can use it as a reference.
Distributed Application
Apsaradb for memcache originally supports distributed architectures. Our client has been slightly transformed to provide better support. Our keys can be properly encapsulated. For example, for a user-based website, each user has a user ID, which can be extracted and accessed based on a fixed ID, for example, users starting with 1 are saved on the first memcache server, and user data starting with 2 is stored on the second child mecache server, data access is converted and accessed according to the user ID.
However, this disadvantage is that you need to determine the user ID. if the business is inconsistent or other types of applications are not suitable, you can consider it based on your actual business, or think about a more appropriate method.
Reduce database pressure
This is important. All the data is basically stored in the database. Each time the database is accessed frequently, the database performance is greatly reduced and it cannot serve more users at the same time, for example, for MySQL, tables with frequent locks, let memcache share the pressure on the database. We need a method that is relatively small and will not change the front-end on a large scale to change the current architecture.
A simple method I want to consider:
The back-end database operation module extracts all select operations (Update, delete, or insert), and then performs corresponding hash operations on the corresponding SQL statements.AlgorithmCalculate a hash data key (such as MD5 or Sha), and then use this key to search for data in memcache. If this data does not exist, it indicates that it has not been written to the cache, then extract the data from the database. One is the array format, and then set the data to memcache. The key is the hash value of the SQL statement, and then set an expiration time accordingly, for example, the data in an hour is extracted from the cache, effectively reducing the pressure on the database. The disadvantage is that the data is not real-time. After the data is modified, it cannot be displayed on the front-end in real time, and memory usage may be high. After all, the number of data in each select operation may be large, this is a factor to consider.
Memcache Security
The above memcache servers are directly connected through the client and there is no verification process. In this way, it is dangerous to directly expose the server to the Internet, if data leaks are viewed by other unrelated personnel, the server is infiltrated because mecache runs with the root permission. Besides, some unknown bugs or buffer overflow may exist, these are all unknown, so the danger is foreseeable. For the sake of security, I have made two suggestions to slightly prevent hacker intrusion or data leakage.
Intranet access
It is recommended that the access between the two servers is in the Intranet format, generally between the Web server and the memcache server. Generally, the server has two NICs, one pointing to the Internet and the other pointing to the Intranet, so that the Web server can access the memcache server through the Intranet Nic, when the memcache server is started, it listens to the Intranet IP address and port, and the access between the Intranet 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 sets listening to port 11211 of the IP address 192.168.0.200 over the Intranet, occupying 1024 MB of memory and allowing a maximum of concurrent connections.
Set firewall
Firewall is a simple and effective method. If both servers are connected to the Internet and memcache needs to be accessed through an Internet IP address, you can use a firewall or proxy program to filter out illegal access.
In Linux, we can use iptables or FreeBSD ipfw to specify rules to prevent unauthorized access. For example, we can set to allow only our web servers to access our memcache server, at the same time, other accesses are blocked.
# 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 access from the Web server 192.168.0.2 to the memcache server. It can effectively prevent some illegal access and add other rules to enhance security, this can be done according to your own needs.