Install memcached and use it in PHP

Source: Internet
Author: User
[Program 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> ";

[Memcache protocol analysis]
If you do not like the php_memcache.dll extension or the server currently does not support this extension, you can consider building your own client. To build a memcahe client, you must first understand the interaction of the memcache protocol, in this way, you can develop your own client. Here I will analyze the following memcache protocols.
(For more detailed protocol content, see the source code DOC/protocol.txt file on the memcache server. This article basically comes from this)
Memcache supports both TCP and UDP protocols, but here we take the TCP protocol as the main consideration object. For more information about the UDP Protocol process, see the doc/protocol.txt file.
[Error command]
The Protocol Error section of memcache contains three error prompts:
Common error messages, such as Command Errors
Error \ r \ n
Client errors
Client_error <error message> \ r \ n
Server errors
Server_error <error message> \ r \ n
[Data Storage command]
Data storage is a basic function, that is, the client returns data through commands, and the server receives and processes the data.
Command Format:
<Command> <key> <tag> <validity period> <data length> \ r \ n
<Command>-Command name
It mainly includes three commands for data storage: Set, add, and replace.
The SET command is to save a data key to the server.
The add command adds data to the server, but the server must not have this key, which ensures that the data will not be overwritten.
The replace command replaces an existing data. If the data does not exist, it is similar to the set function.
<Key>-Key
It is a unique identifier stored on the server. It must not conflict with other keys. Otherwise, the original data will be overwritten. This key is used to accurately access a Data Project.
<Tag>-Flag
A tag is a 16-bit unsigned integer data that is used to set the interaction between the server and the client.
<Validity period>-Expiration time
Is the validity period of data on the server. If it is 0, the data will always be valid, in seconds, the memcache server sets a Data Validity period to the current UNIX time + the set validity period.
<Data length>-Bytes
Data Length: the length of block data blocks. Generally, after the length ends, the next line follows the block data content. After the data is sent, the client generally waits for the server to return, server return:
Data saved
Stored \ r \ n
An error occurred while saving the data, generally because the data key on the server already exists.
Not_stored \ r \ n

[Data extraction command]
The GET command is used to extract data from the server. The format is:
Get <key> * \ r \ n
<Key> *-Key
Key is a combination of non-null strings. After sending this command, wait for the server to return. If the server does not have any data, it returns:
End \ r \ n
This key does not exist and there is no data. If there is data, the specified format is returned:
Value <key> <tag> <data length> \ r \ n
<Data block>\ R \ n
The returned data starts with value, followed by key, flags, and data length, and the second row followed by data blocks.
<Key>-Key
Is the key content of the sent command.
<Tag>-Flags
Is the flags used to call the SET command to save data.
<Data length>-Bytes
Is the positioning length when saving the data
<Data block>-Data Block
The next row is the extracted data block content.

[Data deletion command]
The data deletion command is also relatively simple. Use the GET command in the following format:
Delete <key> <timeout> \ r \ n
<Key>-Key
Key is the key you want to delete data from the server.
<Timeout>-Timeout
The Unit is seconds. This is optional. If you do not specify this value, the key data on the server will be deleted immediately. If this value is set, the data will be cleared after the time-out period. The default value of this item is 0, that is, the data will be deleted immediately.
After the data is deleted, the server returns:
Deleted \ r \ n
Data deleted
Not_found \ r \ n
This key is not found on the server
To delete data from all servers, run the flash_all command in the following format:
Flush_all \ r \ n

After this command is executed, All cached data on the server is deleted and the following response is returned:
OK \ r \ n
This command is generally not easy to use, unless you want to delete all the data, it can not be restored after deletion.

[Other commands]
If you want to know the status and version of the current memcache server, you can use the status query command and version query command.
If you want to know the status of all current memcache servers, you can use the stats command in the format
Stats \ r \ n
The server returns the status information starting from stat for each row, including 20 rows and about 20 items, the information includes the PID, version, number of saved projects, memory usage, and maximum memory limit of the daemon.

If you only want to obtain information about some projects, you can specify the parameter format:
Stats <parameter> \ r \ n
This command returns only the project status information of the specified parameter.
If you only want to know the current version information separately, you can use the version command in the following format:
Version \ r \ n
Returns the version information starting with version.
To end the current connection, use the quit command. format:
Quit \ r \ n
Will disconnect the current connection
In addition, there are other commands, including incr and decr. If you are interested, you can study them on your own.

[Use of memcache on medium-sized websites]
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 userid, 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.
[Reducing 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/insert ), then, calculate the corresponding SQL statement using the corresponding hash algorithm to obtain a hash data key (such as MD5 or Sha), and then query the key in memcache for data. If the data does not exist, it indicates that the data has not been written into the cache, so the data is extracted from the database. One is the array format, and the data is then set to memcache. The key is the hash value of this SQL statement, then set an expiration time, for example, one hour. The data in one 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.
The above is just a simple idea that I have not considered. It may be useful.

[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 a 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.

[Memcache scalability]
Memcache is a simple and efficient program. The source code size of memcache 1.2.0 is only 139 KB, Which is unimaginable on the Windows platform. However, in the Open Source world, this is normal and reasonable.
Memcache is currently only a simple function, simple data access function, I personally hope that if people of insight, can be expanded in the following two aspects.
1. log function
Currently, memcache does not have the log function, and only some commands are displayed on the server. This is not conducive to monitoring the Stability and Load of a server, it is best to add functions such as logs to facilitate monitoring.
2. Storage Structure
The current data format is: Key => data, which is very simple. It can only store a single one-dimensional data. If it can be expanded, it will become a database-like format and can store two-dimensional data, this will make it more usable and more widely used. Of course, the code efficiency and access efficiency may be worse.
3. Synchronization
Data Synchronization is an important technology, because no one can ensure that a server runs normally. If it can have functions similar to MySQL Master/Slave, this will make memcache data more stable, so you can consider storing persistent data, and do not have to worry about the memcache down, because there is a synchronous backup server, this is not a problem.
The above three points are only personal opinions. You can consider them with insight and technical experts.

[Conclusion]
The content above is just some of my own installation and use ideas. It cannot be guaranteed to be absolutely correct. I just want to give a reference to anyone who needs it and an article that promotes memcache, we hope that more people can understand and use this technology for their own purposes.
It took me a whole night to write so much, but I love this open-source technology. I think the open-source world can flourish, it is because of everyone's love and willingness to make contributions that the Open Source world is so wonderful.
I hope this article will help people who need it, and I hope it will not mislead them.

Additional: (the image corresponding to the content of the above article corresponding to my memcache Operation)
[Start memcache]



[Memcache PHP test code]

[Test code execution results]

[Connect to memcache via Telnet]


[Basic memcache Data Access Protocol interaction]

[Memcache status information protocol interaction]
 

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.