Use memcache in PHP to optimize Buffer Performance

Source: Internet
Author: User

PHP memcache

<? 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:

ProgramCodeAnalysis

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.

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.

setting a firewall
Firewall is a simple and effective method. If both servers are on the Internet and you need to use an Internet IP address to access memcache, you can use a firewall or proxy program to filter out unauthorized access.
in Linux, you can use iptables or ipfw in FreeBSD to specify rules to prevent unauthorized access, for example, we can set to allow only our web servers to access our memcache server and block other accesses.
# 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 block some illegal access and add other rules to enhance security. This can be done according to your own needs.

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.