Memcache Cache Explanation

Source: Internet
Author: User
Tags memcached server port

This article mainly introduces the PHP memcache, starting from the memcache introduction, in detail, such as memcache and memcached differences, PHP memcache all the operation methods, each operation method of the detailed explanation, the need for friends can refer to the next
I. Introduction of Memcache
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 and then building a hashtable,memcached to manage these hashtable, it's very fast.

Ii. the difference between memcache and memcached

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.

Third, Memcache server-side and client Installation

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.

Iv. Summary of all methods of PHP Memcache client

The list of all methods for the Memcache function is as follows:
Memcache::add– adds a value that returns false if it already exists
memcache::addserver– Add a server address that is available for use
memcache::close– Close a Memcache object
memcache::connect– Creating a Memcache Object
memcache_debug– Control Debugging function
Memcache::d ecrement– to subtract a value from a saved key
Memcache::d elete– Delete a key value
memcache::flush– to clear all cached data
memcache::get– get a key value
memcache::getextendedstats– get run System statistics for all processes in the process pool
memcache::getserverstatus– getting parameters to run the server
memcache::getstats– returns some running statistics for the server
memcache::getversion– returns the version information of the running Memcache
memcache::increment– an addition to the value in a saved key
Memcache: Create a Memcache Persistent connection object:p connect–
Memcache::replace-Overwrite an existing key
Memcache::set– adds a value that, if already present, overwrite
memcache::setcompressthreshold– compression of data larger than a certain size
memcache::setserverparams– modifying the server's parameters at run time

V. Memcache operation method Decomposition of PHP

Memcache::add usage
The code is as follows: BOOL Memcache::add (String $key, mixed $var [, int $flag [, int $expire]])

Description
If $key does not exist, use this function to store the value of $var. Functions with the same function are Memcache_add ().

Parameters:
$key: The key value that will be stored.
$var: Stored values, character types and integers are saved as original values, and other types are automatically serialized for later saving.
$flag: Whether the stored value is compressed with memcache_compressed, true means compression, and false means no compression.
$expire: The expiration time of the stored value, if 0 means it will not expire, you can use the Unix timestamp or description to indicate the time from now, but when you use the number of seconds to represent, do not exceed 2.592 million seconds (for 30 days).

return value:
Returns TRUE if successful, and FALSE if it fails. If the $key value already exists, it returns false. In other cases, the usage of Memcache::add () is similar to Memcache::set ().
Example:

The code is as follows:
Add (' Var_key ', ' Test variable ', false, 30);
?>

Memcache::addserver usage
The code is as follows: BOOL Memcache::addserver (string $host [, int $port [, bool $persistent [, int $weight [, int$timeout [, int $retry _ interval [, BOOL $status [, Callback $failure _callback]] []]

Description
Add an available server address to the connection pool, the connection is opened with Memcache::addserver, the script is closed automatically after execution, or it can be closed manually with Memcache::close (). The same function is Memcache_add_server ().
When using this method (relative to Memcache::connect () and Memcache::p the Connect () method), the network connection will only be established when needed, so it will not increase the system burden by adding a lot of servers to the connection pool. Because many servers may not be used.
Failback occurs at any stage of this method execution, and as long as the other servers are normal, the failed users of these connection requests will not notice. Any type of socket or memcached server-level error can trigger a failure recovery. Normal client-side errors such as adding an existing key value do not cause a failure recovery.

Parameters:
Address of the $host server
$port Server Port
$persistent whether it is a persistent connection
$weight the weight that this server takes on all servers
Duration of $timeout Connection
$retry _interval Connection retry interval, default is 15, set to 1 means no retries
$status control the online status of the server
$failure _callback allows you to set a fallback function to handle error messages.

return value:
Returns TRUE if successful, and FALSE if it fails.

Example:
The code is as follows: Addserver (' Memcache_host ', 11211);
$memcache->addserver (' memcache_host2′, 11211);

$memcache _obj = memcache_connect (' memcache_host ', 11211);
Memcache_add_server ($memcache _obj, ' memcache_host2′, 11211);
?>

Memcache::close usage

BOOL Memcache::close (void)

Description
Close the Memcache server connection. This function does not close long connections, and long connections are closed only when the Web server is shut down or restarted. The same function memcache_close ()
return value:
Returns TRUE if successful, and FALSE if it fails.
Example:

The code is as follows:
Connect (' Memcache_host ', 11211);
$memcache _obj->close ();
?>

Memcache::connect usage
The code is as follows: BOOL Memcache::connect (string $host [, int $port [, int $timeout]]

Description
Open the Memcached server connection, establish a connection to the memcached server, and the connection opened with Memcache::connect automatically shuts down after the script is executed. You can also use Memcache::close () to close the connection. The same function is Memcache_connect ().
Parameters:
$host: To the host of the link memcached is listening to, this parameter will have another special connection method Unix:///path/to/memcached.sock, that is, with the UNIX domain name sockets, in which case the port must be set to 0
$port: To the port where memcached is listening to the link, the port must be set to 0 with the UNIX domain name sockets
$timeout: The number of seconds to connect to the daemon, when you change the default value of 1 seconds, you need to consider that if your connection is too slow, you may lose the advantage of caching.

return value:
Returns TRUE if successful, and FALSE if it fails.
Example:
The code is as follows:
Connect (' Memcache_host ', 11211);

?>

Memcache::d ebug

The code is as follows: BOOL Memcache_debug (bool $on _off)

Description
Controls debug functionality, provided PHP uses the-enable-debug option when compiling, otherwise this function will not work.
Parameters:
$on _off:true to turn on debugging, false to turn off debugging
return value:
If PHP uses the-enable-debug option when compiling, returns true, otherwise false

Memcache::d ecrement usage
The code is as follows: int Memcache::d ecrement (String $key [, int $value])

Description
Memcache: The function of the:d Ecremen method is to subtract from the value in a saved key, similar to memcache::increment.
You can also use the memcache_decrement () function.
Parameters:
Key: The name of the keys you want to reduce
Value: The values that you want to decrease.

return value:
If successful, returns the value after being reduced if the failure returns false.
Example:

The code is as follows:
Connect (' localhost ', 11211);
$memcache->set (' Test_item ', 8);
$memcache->increment (' Test_item ', 4);
echo $memcache->decrement (' Test_item ', 7);
Showing 5
?>

This example even memcache::increment functions are shown in a piece.

Memcache::d elete Usage

The code is as follows: BOOL Memcache::d elete (String $key [, int $timeout])

Description
Delete a key value, if the parameter $timeout is set, then the stored value will expire after the set number of seconds, you can also use the function Memcache_delete ()

return value:
Returns TRUE if successful, and FALSE if it fails.

Example:
The code is as follows:
Connect (' Memcache_host ', 11211);
$memcache _obj->delete (' Key_to_delete ', 10);

?>

Memcache::flush
The code is as follows: BOOL Memcache::flush (void)

Description
Clears all cached data. Memcache::flush does not actually release resources, it simply marks all caches as expired, which allows the new cache to overwrite the occupied memory space. The same function is Memcache_flush ()

return value:
Returns TRUE if successful, and FALSE if it fails.

Example:

The code is as follows:
Connect (' Memcache_host ', 11211);

$memcache _obj->flush ();

?>

Memcache::get

The code is as follows:
String Memcache::get (string $key [, int & $flags])

Array memcache::get (array $keys [, Array & $flags])

Description
The function of the method is to get a key value, which can be an array, and the result will contain a key-value pair.

Parameters:
$key is the value of a key or an array of keys.
$flags If this parameter exists, then $flags is related to the value written to this parameter, and these $flags are similar to the $flags in the Memcache::set () function.

return value:
If successful, returns the value corresponding to key and returns False if it fails.
Example:
The code is as follows:
Connect (' Memcache_host ', 11211);
$var = $memcache _obj->get (' Some_key ');

$memcache _obj = memcache_connect (' memcache_host ', 11211);
$var = Memcache_get ($memcache _obj, Array (' Some_key ', ' Another_key '));

$memcache _obj = new Memcache;
$memcache _obj->connect (' Memcache_host ', 11211);
$var = $memcache _obj->get (Array (' Some_key ', ' Second_key '));

?>

Memcache::getextendedstats
The code is as follows: Array memcache::getextendedstats ([string $type [, int $slabid [, int $limit]])

Description
Gets the running system statistics for all processes in the process pool. The same function is Memcache_get_extended_stats ()

Parameters:
$type indicates the type of return required: RESET, malloc, maps, Cachedump, slabs, items, sizes;
$slabid used when the first parameter is set to "Cachedump".
$limit used when the first parameter is set to "Cachedump".
return value:
If successful, the statistics are returned, and the failure returns false

Example:
The code is as follows:
Addserver (' Memcache_host ', 11211);
$memcache _obj->addserver (' Failed_host ', 11211);

$stats = $memcache _obj->getextendedstats ();
Slabs mechanism allocation of memory management
$statsslab = $memcache _obj->getextendedstats (slabs);

?>

Memcache::getserverstatus

The code is as follows: int memcache::getserverstatus (string $host [, int $port])

Description
Gets the parameters that run the server. Returns the status of a server online or offline. The same function is Memcache_get_server_status ()

Parameters:
$host: The host of the connection you are listening to
$port the port of the host to which the connection is being tuned, the default is 11211

return value:
Successful return to the server state, the server does not start will return 0, the other number when the server is a startup state.

Example:
The code is as follows:
Addserver (' Memcache_host ', 11211);
echo $memcache->getserverstatus (' Memcache_host ', 11211);

$memcache = Memcache_connect (' memcache_host ', 11211);
Echo memcache_get_server_status ($memcache, ' memcache_host ', 11211);

?>

Memcache::getstats

The code is as follows: Array memcache::getstats ([string $type [, int $slabid [, int $limit]])

Description
Returns some run statistics for the server. The same function is Memcache_get_stats ()

Parameters:
$type indicates the type of return required: RESET, malloc, maps, Cachedump, slabs, items, sizes;
$slabid used when the first parameter is set to "Cachedump".
$limit used when the first parameter is set to "Cachedump".

Memcache::getversion
The code is as follows: String memcache::getversion (void)

Description
Returns the version information of the running memcache. Same function memcache_get_version ()

return value:
The version information of the server is returned successfully, and false is returned when it fails.

Example:
The code is as follows:
Connect (' Memcache_host ', 11211);
echo $memcache->getversion ();

$memcache = Memcache_connect (' memcache_host ', 11211);
echo memcache_get_version ($memcache);
?>

Memcache::increment

The code is as follows: int memcache::increment (string $key [, int $value])

To add an addition to a value in a saved key
Usage reference memcache::d ecrement

Memcache::p Connect

The code is as follows: BOOL Memcache::p Connect (string $host [, int $port [, int $timeout]])

Description
To create a Memcache persistent connection object
Usage is similar to Memcache::connect (), where the difference is memcache::p Connect is a persistent connection established. This connection is not closed when the script finishes or the Memcache::close () function is run. The function that is the same as it is Memcache_pconnect ()

Parameters:
$host: To the host of the link memcached is listening to, this parameter will have another special connection method Unix:///path/to/memcached.sock, that is, with the UNIX domain name sockets, in which case the port must be set to 0
$port: To the port where memcached is listening to the link, the port must be set to 0 with the UNIX domain name sockets
$timeout: The number of seconds to connect to the daemon, when you change the default value of 1 seconds, you need to consider that if your connection is too slow, you may lose the advantage of caching.

return value:
Returns TRUE if successful, FALSE if unsuccessful
The code is as follows:
Pconnect (' Memcache_host ', 11211);

?>

Memcache::replace
The code is as follows: BOOL Memcache::replace (String $key, mixed $var [, int $flag [, int $expire]])

Description
Overwrite an existing key. The same function is Memcache_replace ()

Parameters:
$key: The key value that will be stored.
$var: Stored values, character types and integers are saved as original values, and other types are automatically serialized for later saving.
$flag: Whether the stored value is compressed with memcache_compressed, true means compression, and false means no compression.
$expire: The expiration time of the stored value, if 0 means it will not expire, you can use the Unix timestamp or description to indicate the time from now, but when you use the number of seconds to represent, do not exceed 2.592 million seconds (for 30 days).

return value:
Returns TRUE if successful, and FALSE if it fails. If the $key value already exists, it returns false.
The code is as follows:
Replace ("Test_key", "some variable", false, 30);

?>

Memcache::set
The code is as follows: BOOL Memcache::set (String $key, mixed $var [, int $flag [, int $expire]])

Description
Adds a value that, if it already exists, is overwrite. The same function is Memcache_set ()

Parameters:
$key: The key value that will be stored.
$var: Stored values, character types and integers are saved as original values, and other types are automatically serialized for later saving.
$flag: Whether the stored value is compressed with memcache_compressed, true means compression, and false means no compression.
$expire: The expiration time of the stored value, if 0 means it will not expire, you can use the Unix timestamp or description to indicate the time from now, but when you use the number of seconds to represent, do not exceed 2.592 million seconds (for 30 days).

return value:
Returns TRUE if successful, and FALSE if it fails.

Example:

The code is as follows:
$memcache _obj = new Memcache;
$memcache _obj->connect (' Memcache_host ', 11211);
$memcache _obj->set (' Var_key ', ' Some really big variable ', memcache_compressed, 50);
echo $memcache _obj->get (' Var_key ');

Memcache::setcompressthreshold
The code is as follows: BOOL Memcache::setcompressthreshold (int $threshold [, float $min _savings])

Description
Compress data that is larger than a certain size. The same function is Memcache_set_compress_threshold ()

Parameters:
The Setcompressthreshold method has two parameters, the first parameter represents the critical point of processing the data size, the second parameter represents the scale of the compression, and the default is 0.2.

return value:
Returns TRUE if successful, and FALSE if it fails.

Example:
The code is as follows:
Addserver (' Memcache_host ', 11211);
$memcache _obj->setcompressthreshold (20000, 0.2);

$memcache _obj = memcache_connect (' memcache_host ', 11211);
Memcache_set_compress_threshold ($memcache _obj, 20000, 0.2);

?>

Memcache::setserverparams

Copy the code code as follows: BOOL Memcache::setserverparams (string $host [, int $port [, int $timeout [, int$retry_interval [, BOOL $status [, Callback $failure _callback]]] )

Description
Modifies the server's parameters at run time. The same function is Memcache_set_server_params ().

Parameters:
Address of the $host server
$port Server Port
Duration of $timeout Connection
$retry _interval Connection retry interval, default is 15, set to 1 means no retries
$status control the online status of the server
$failure _callback allows you to set a fallback function to handle error messages.

return value:
Returns TRUE if successful, and FALSE if it fails.

Example:
The code is as follows:
Addserver (' Memcache_host ', 11211, False, 1, 1,-1, false);

Set up the server as an online
$memcache->setserverparams (' Memcache_host ', 11211, 1, A, true, ' _callback_memcache_failure ');

$memcache _obj = memcache_connect (' memcache_host ', 11211);
Memcache_set_server_params ($memcache _obj, ' memcache_host ', 11211, 1, A, true, ' _callback_memcache_failure ');

?>

Vi. Examples of integrated use
The code is as follows:
Connect ("Db.nowamagic.net", 12000);
Save data
$mem->set (' key1′, ' This is first value ', 0, 60);
$val = $mem->get (' key1′);
echo "Get Key1 value:". $val. "
“;
Replace data
$mem->replace (' key1′, ' This is replace value ', 0, 60);
$val = $mem->get (' key1′);
echo "Get Key1 value:". $val. “
“;
Save Array
$arr = Array (' AAA ', ' BBB ', ' CCC ', ' ddd ');
$mem->set (' key2′, $arr, 0, 60);
$val 2 = $mem->get (' key2′);
echo "Get Key2 value:";
Print_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:";
Print_r ($val 2);
echo "
“;
Close connection
$mem->close ();
?>

If normal, the browser will output:
The code is as follows:
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:

Vii. code Analysis of the instance program

Initializes an Memcache object: $mem = new Memcache;
Connect to our Memcache server, the first parameter is the IP address of the server, 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:

The code is as follows:
$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:
The code is as follows:
$mem->replace (' key1′, ' This is replace value ', 0, 60);
$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:
The code is as follows:
$arr = Array (' AAA ', ' BBB ', ' CCC ', ' ddd ');
$mem->set (' key2′, $arr, 0, 60);
$val 2 = $mem->get (' key2′);
Print_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:
The code is as follows: $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:
The code is as follows: $mem->flush ();
$val 2 = $mem->get (' key2′);
echo "Get Key2 value:";
Print_r ($val 2);
echo "
“;

Viii. when to use the Memcache and memcache environment

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, then can be based on a fixed ID to extract and access, such as 1, the beginning of the user is saved on the first memcache server, the user's data beginning with 2 is saved in the second child On the Mecache server, the 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.

IX. Safety of Memcache

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.
Copy the code code as follows: # 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.
Copy the code code as follows: # 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.

Memcache Cache Explanation

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.