_php instance of installing and using memcache in PHP environment

Source: Internet
Author: User
Tags flush memcached

Memcache is a danga.com project, the first to serve the LiveJournal, many people around the world use this cache project to build their own heavy load of the site to share the pressure of the database. It can handle any number of connections and use non-blocking network IO. Because its working mechanism is to open up a space in memory, and then establish a hashtable,memcached self management of these hashtable. Memcache Official website: http://www.danga.com/memcached, more detailed information can come here to understand.

Why are there memcache and memcached two kinds of names? In fact Memcache is the name of this project, and memcached is its server-side main program file name, know what I mean put ~ ~ ~ ~ ~ One is the project name, one is the main program file name, on the internet to see a lot of people do not understand, so mixed use.

Installation of Memcache

Divided into two procedures: Memcache server-side installation and memcached client installation.
The so-called server-side installation is on the server (typically Linux system) on the installation of Memcache implementation data storage.
The so-called client installation means PHP (or other programs, memcache and other good API interface) to use the server-side memcache provided functions, the need for PHP to add extensions.

PHP's Memcache

<?php
  //connection
  $mem = new Memcache;
  $mem->connect ("db.nowamagic.net",);
  Save Data
  $mem->set (' key ', ' This is the ', ');
  $val = $mem->get (' key ');
  echo "Get key value:". $val. " <br/> ";
  Replace data
  $mem->replace (' key ', ' is replace value ',,);
  $val = $mem->get (' key ');
  echo "Get key value:". $val. "<br/>";
  Save Arrays
  $arr = Array (' AAA ', ' BBB ', ' CCC ', ' ddd ');
  $mem->set (' key ', $arr,,);
  $val = $mem->get (' key ');
  echo "Get key value:";
  Print_r ($val);
  echo "<br/>";
  Delete Data
  $mem->delete (' key ');
  $val = $mem->get (' key ');
  echo "Get key value:". $val. "<br/>";
  Clear all data
  $mem->flush ();
  $val = $mem->get (' key ');
  echo "Get key value:";
  Print_r ($val);
  echo "<br/>";
  Close the connection
  $mem->close ();
? >

If normal, the browser will output:

Get Key Value:this is a
Get key value:this is replace value
Get key Value:array ([] => AAA [] => BBB [] => CCC [] => DDD)
Get key value:
Get key value:

Program Code Analysis

Initializes a Memcache object: $mem = new Memcache;
Connect to our Memcache server, the first parameter is the IP address of the server, can also be the hostname, the second parameter is memcache open port: $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 to save the data content, here is a string, the third parameter is a tag, generally set to 0 or memcache_compressed on the line, The fourth parameter is the validity period of the data, that is, the data in this time is valid, if the past this time, then will be Memcache server side to clear the data, unit is seconds, if set to 0, is always valid, we set up here 60, is a minute effective time: $mem-> Set (' Key1 ', ' This is the ' is a ', 0, 60);

From the Memcache server to get a data, it has only one parameter, is the need to obtain data key, we here is the previous step set Key1, now get this data output output:

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

Instead of replacing the Key1 value with the Replace method, 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, and the last output is:

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

Similarly, memcache can also save an array, and the following is an array stored on the memcache and then fetched back and output:

$arr = Array (' AAA ', ' BBB ', ' CCC ', ' ddd ');
$mem->set (' key ', $arr,,);
$val = $mem->get (' key ');
Print_r ($val);

Now deletes a data, uses the Delte interface, the parameter is a key, then can delete the Memcache server This key data, the final output time does not have the result:

$mem->delete (' key ');
$val = $mem->get (' key ');
echo "Get key value:". $val. "<br/>";

Finally, we have all the data saved on the Memcache server cleared, we will find that the data is gone, the final output key2 data is empty, and finally close the connection:

$mem->flush ();
$val = $mem->get (' key ');
echo "Get key value:";
Print_r ($val);
echo "<br/>";

The use of Memcache

Use Memcache Web site general traffic is relatively large, in order to ease the pressure of the database, so that memcache as a cache area, the part of the information stored in memory, the front-end can be accessed quickly. So the general focus is on how to share the database pressure and distributed, after all, the single memcache memory capacity of the limited. I am here to briefly present my personal views, without practice, right as a reference.

Distributed applications

Memcache originally supported the distributed, our client slightly modified, better support. Our key can be properly packaged in a regular way, for example, user-oriented Web sites, each users have user ID, you can follow a fixed ID for extraction and access, such as 1 of users at the beginning of the first memcache server, The data of the user starting with 2 is stored on the second Mecache server, and the access data is converted and accessed according to the user ID first.

But the disadvantage is that you need to judge the user ID, if the business is inconsistent, or other types of applications may not be so appropriate, then you can consider the actual business, or think of a more appropriate method.

Reduce database pressure

This is more important, all the data are basically kept in the database, every time the frequent access to the database, resulting in a very degraded database performance, can not serve more users at the same time, such as MySQL, particularly frequent lock table, so let memcache to share the pressure of the database. We need a way to change the current architecture by making small changes that will not change the front end on a large scale.

One simple way I consider:

The back-End Database operation module, which extracts all select operations (Update/delete/insert), and then calculates the corresponding hash algorithm for the corresponding SQL to calculate a hash data key (such as MD5 or SHA), Then the key to Memcache to find data, if this data does not exist, the description has not been written to the cache, then from the database to extract the data, one is the array class format, and then the data in set to Memcache, key is the hash value of this SQL, Then the corresponding setting of a failure time, such as one hours, then one hours of data are extracted from the cache, effectively reduce the pressure on the database. The disadvantage is that the data is not real-time, when the data has been modified, can not be real-time to the front end display, and there may be a larger memory footprint, after all, the number of select data may be large, this is a factor to consider.

The safety of Memcache

Our above Memcache server side is directly through the client connection directly after the operation, without any verification process, so if the server is directly exposed to the Internet is more dangerous, light data leakage by other unrelated personnel to view, heavy server was invaded, Because the Mecache is run as root, and there may be some unknown bugs or buffer overflows, these are unknown, so the danger is predictable. To be on the safe side, I make two suggestions that can be a little bit of protection against hacking or data leaks.

Intranet access

It is best to access the two servers in the intranet form, typically between the Web server and the Memcache server. Universal servers are two network cards, a point to the Internet, a point to the intranet, then let the Web server through the intranet network card to access the Memcache server, we memcache the server on the start of the monitoring intranet IP address and port, 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-side setting listens for 11211 ports of 192.168.0.200 IP through the intranet, consumes 1024MB of memory, and allows up to 1024 concurrent connections.

Setting up Firewalls

Firewall is a simple and effective way, if it is two servers are hanging in the net, and need to access memcache through the extranet IP, then you can consider using a firewall or agent program to filter illegal access. In general, we can use Iptables or FreeBSD under Linux to specify some rules to prevent illegal access, such as we can set up only 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 iptables rule above is to allow only 192.168.0.2 this Web server access to the Memcache server, can effectively prevent some illegal access, the corresponding can also add some other rules to enhance security, this can be done according to their 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.