How to use Memcache in PHP environment _php tutorial

Source: Internet
Author: User
Memcache is a danga.com project, the first to serve 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, using non-blocking network IO. Because it works by opening up a space in memory, it then builds a hashtable,memcached self-managing these hashtable. Memcache Official website: http://www.danga.com/memcached, more detailed information can come here to understand.

Why are there two names of Memcache and memcached? In fact Memcache is the name of this project, and memcached is its server side of the main program file name, know what I mean to 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.

Installation of Memcache

It is divided into two processes: Memcache server-side installation and memcached client installation.

The so-called server-side installation is to install Memcache on the server (generally Linux system) to implement data storage.

The so-called client installation refers to PHP (or other programs, memcache and other good API interface) to use the server-side memcache provided functions, PHP needs to add extensions.

PHP's Memcache

 
  Connect ("db.bkjia.com", 12000);//Save Data $mem->set (' Key1 ', ' This is first value ', 0, $); $val = $mem->get (' Key1 '); echo "Get Key1 value:". $val. "
";//Replace Data $mem->replace (' Key1 ', ' This is replace value ', 0, $); $val = $mem->get (' key1 '); echo" Get Key1 Value: ". $val. "
";//save Array $arr = Array (' AAA ', ' BBB ', ' CCC ', ' ddd '); $mem->set (' Key2 ', $arr, 0); $val 2 = $mem->get (' Key2 '); echo" Get Key2 value: ";p rint_r ($val 2); echo"
";//delete Data $mem->delete (' Key1 '); $val = $mem->get (' key1 '); echo" Get Key1 Value: ". $val. "
";//Clear All data $mem->flush (); $val 2 = $mem->get (' Key2 '); echo" Get Key2 Value: ";p rint_r ($val 2); echo"
";//close connection $mem->close ();? >

If normal, the browser will output:

Get Key1 Value:this is first valueget key1 value:this is replace Valueget key2 Value:array ([0] = = AAA [1] = BB b [2] = CCC [3] = DDD) Get key1 value:get key2 Value:

Program Code Analysis

Initializes an Memcache object: $mem = new Memcache;

Connect to our Memcache server side, the first parameter is the server's IP address, it can be the hostname, 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 to save the data content, here is a string, the third parameter is a marker, 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 the memcache server side will be purged of this data, the unit is seconds, if set to 0, it is always valid, we set up here 60, is a minute effective time: $mem Set (' Key1 ', ' This is first value ', 0, 60);

Get a piece of data from the Memcache server, it has only one parameter, is the key that needs to get the data, we here is the key1 that the previous step sets, now obtains this data after output:

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

Instead of replacing the value of the above key1 with the Replace method, the Replace method parameter is the same as set, but the first parameter, Key1, must be the key to replace the data content, and the final output is:

$mem->replace (' key1 ', ' This is replace value ', 0, $); $val = $mem->get (' key1 '); echo "Get Key1 Value:". $val;

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

$arr = Array (' AAA ', ' BBB ', ' CCC ', ' DDD '), $mem->set (' Key2 ', $arr, 0), $val 2 = $mem->get (' Key2 ');p Rint_r ($val 2);

Now delete a data, using the Delte interface, the parameter is a key, and then can be the Memcache server This key data delete, the final output when there is no result:

$mem->delete (' Key1 '); $val = $mem->get (' key1 '); echo "Get Key1 Value:". $val. "
";

Finally, we put all the data stored on the Memcache server erased, we will find that the data is not, the final output key2 data is empty, and finally close the connection:

$mem->flush (); $val 2 = $mem->get (' Key2 '); echo "Get Key2 Value:";p rint_r ($val 2); echo "
";

Use of Memcache

The use of Memcache website general traffic is relatively large, in order to alleviate the pressure of the database, let Memcache as a cache area, the part of the information stored in memory, in the front-end can be quickly accessed. Then the general focus is to focus on how to share the database pressure and distributed, after all, the memory capacity of a single memcache limited. Here I briefly put forward my personal views, without practice, right when reference.

Distributed applications

Memcache originally support distributed, our client a little transformation, better support. Our key can be appropriately in a regular package, such as the user-oriented site, each users have a customer ID, you can follow a fixed ID to extract and access, such as 1, the beginning of the user is saved on the first memcache server, Data for users starting with 2 are saved on the second Mecache server, and access data is converted and accessed according to the user ID first.

However, this has the disadvantage that the user ID needs to be judged, if the business is inconsistent, or other types of applications may not be appropriate, then according to their actual business to consider, or to think of a more appropriate method.

Reduce database pressure

This is more important, all the data is basically stored in the database, every time the database is frequently accessed, resulting in a very slow database performance, can not serve more users at the same time, such as MySQL, especially frequent lock table, then let memcache to share the pressure of the database. We need to change the current architecture in a way that is small and does not change the front-end on a large scale.

An easy way for me to consider:

Back end of the database operation module, all the select operation is extracted (Update/delete/insert no matter), and then the corresponding SQL for the corresponding hash algorithm to calculate a hash data key (such as MD5 or SHA), Then the key to Memcache to find the data, if the data does not exist, the description has not been written to the cache, then extract the data from the database, an array class format, and then the data in set to Memcache, key is the SQL hash value, 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 of 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 large memory footprint, after all, the number of select out of the data may be relatively large, this is a factor to consider.

Memcache's Safety

Our above Memcache server is directly through the client connection after direct operation, there is no verification process, so if the server is directly exposed to the Internet is more dangerous, light data leakage by other unrelated personnel view, heavy server was compromised, Because the Mecache is run as root, and there may be some of our unknown bugs or buffer overflow situation, these are unknown to us, so the danger is predictable. For the sake of safety, I do two suggestions, can be a little to prevent hacking or data leakage.

Intranet access

It is best to put the access between the two servers in the intranet form, usually between the Web server and the Memcache server. Universal servers are two network card, 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 on the server when the boot on the network to listen to the IP address and port, Access between the intranet can effectively block 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 on the 11211 port of the 192.168.0.200 IP over the intranet, consumes 1024MB of memory, and allows a maximum of 1024 concurrent connections.

Set up a firewall

Firewall is a simple and effective way, if the two servers are hanging in the network, and need to access the Memcache through the extranet IP, then you can consider using a firewall or agent to filter illegal access. Generally we can use iptables or FreeBSD under the Linux under the IPFW to specify some rules to prevent some illegal access, such as we can set 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 192.168.0.2–dport 11211-j accept# iptables-a INPUT- P udp-s 192.168.0.2–dport 11211-j ACCEPT

The iptables rule above is to allow only 192.168.0.2 this Web server to the Memcache server access, can effectively prevent some illegal access, the corresponding can also add some other rules to enhance security, which can be done according to their own needs.

http://www.bkjia.com/PHPjc/752433.html www.bkjia.com true http://www.bkjia.com/PHPjc/752433.html techarticle Memcache is a project of danga.com, the earliest is for LiveJournal service, now 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 ...

  • 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.