Home >Backend Development >PHP Tutorial >Introduction to memcache
memcached is a high-performance distributed memory cache server. Developed by the development team of foreign community website LIVEJOURNAL.
Purpose of use:
Reduce the number of database accesses by caching database query results to increase the speed and scalability of dynamic web applications.
memcache is a free and open source, high-performance, distributed memory object caching system. Used to accelerate dynamic web applications and reduce database load.
Characteristics of memcahce
1. Based on C/S architecture, simple protocol
2. Based on libevent event processing {libevent is a Network library based on event triggering, suitable for multiple platforms such as windows, Linux, bsd (Unix derivative system)}
3. Built-in memory storage method
4. Client-based memcached distribution Formula
Applicable scenarios
1. Distributed deployment is required (what is distributed: If a task has 10 sub-tasks, put these 10 sub-tasks on 10 servers separately, greatly Shorten task execution time,)
2. Need to access the same data frequently
3. Need to share data
Introduction to C/S architecture
Installation startup (see PDF document)
Use of various commands
set/add/replace/delete/get/gets/cas/stats/stats items/ append/prepend/flush_all, etc.
memcahced some features and limitations
①The amount of item data that can be saved in Memcached is not limited, only the memory is enough
②Memcached single The maximum memory used by the process is 2G. To use more memory, you can open multiple Memcached processes on multiple ports
③The maximum data expiration time is 30 days. If it is set to permanent, it will also expire at this time. Constant REALTIME_MAXDELTA
④60*60*24*30 control
⑤The maximum key length is 250 bytes, larger than this length cannot be stored, constant KEY_MAX_LENGTH 250 control
⑥The maximum key length of a single item The data is 1MB. Data exceeding 1MB will not be stored. It is controlled by the constant POWER_BLOCK 1048576.
⑦It is the default slab size
⑧The maximum number of simultaneous connections is 200, through conn_init() freetotal is used to control, the maximum number of soft connections is 1024, controlled through
⑨settings.maxconns=1024⑩Parameters related to space occupation: settings.factor=1.25, settings.chunk_size=48, affecting the data occupation of slab And step by step method
Summary of all methods of PHP’s Memcache client
The list of all methods of memcache function is as follows:
Memcache::add – Add a value, If it already exists, return false
Memcache::addServer - Add a server address for use
Memcache::close - Close a Memcache object
Memcache::connect - Create a Memcache object
memcache_debug - Control the debugging function
Memcache::decrement - Subtract the value in a saved key
Memcache::delete - Delete a key value
Memcache::flush - Clear all cached data
Memcache::get - Get a key value
Memcache::getExtendedStats - Get the running system statistics of all processes in the process pool
Memcache::getServerStatus - Get the parameters of the running server
Memcache::getStats - Return some running statistics of the server
Memcache::getVersion - Return the version information of the running Memcache
Memcache::increment - Add the value in a saved key
Memcache::pconnect - Create a Memcache persistent connection object
Memcache::replace - Overwrite an existing key
Memcache::set - Add a value, if it already exists, overwrite
Memcache: :setCompressThreshold – Compress data larger than a certain size
Memcache::setServerParams – Modify server parameters at runtime
Decomposition of PHP’s Memcache operation method
Memcache::add usage
Description:
If $key does not exist, use this function to store the value of $var. The functionally equivalent function is memcache_add().
Parameters:
$key: The key value to be stored.
$var: The stored value, character type and integer type will be saved as the original value, other types will be automatically serialized and saved later.
$flag: Whether to use MEMCACHE_COMPRESSED to compress the stored value, true means compression, false means no compression.
$expire: The expiration time of the stored value. If it is 0, it means it will not expire. You can use a unix timestamp or description to represent the time from now, but when you use seconds to express it, it should not exceed 2592000 seconds. (meaning 30 days).
Return value:
Return TRUE if successful, return FALSE if failed. If the $key value already exists, FALSE will be returned. In other cases, the usage of Memcache::add() is similar to Memcache::set().
Example:
Memcache::addServer usage
Description:
Add a usable server address to the connection In the pool, the connection is opened with Memcache::addServer and automatically closed after the script is executed, or it can be closed manually with Memcache::close(). The same function is memcache_add_server().
When using this method (compared to the Memcache::connect() and Memcache::pconnect() methods), the network connection will only be established when needed, so there will be no need to add many servers to the connection pool. And increase the system burden, because many servers may not be used.
Failure recovery will occur at any stage of the execution of this method. As long as other servers are normal, users will not notice the failure of these connection requests. Any kind of socket or memcached server-level error can trigger failover. Normal client errors such as adding an existing key will not trigger failover.
Parameters:
$host server address
$port server port
Whether $persistent is a persistent connection
$weightThe weight of this server among all servers
$timeout connection duration
$retry_intervalThe interval between connection retries, the default is 15, set to -1 means no retry
$status controls the online status of the server
$failure_callback allows setting A callback function to handle error messages.
Return value:
Return TRUE if successful, return FALSE if failed.
Example:
Memcache::close usage
bool Memcache::close (void)
Description:
Close the memcache server connection. This function will not close the long connection. The long connection will only be closed when the web server is shut down or restarted. The same function memcache_close()
Return value:
Returns TRUE if successful, returns FALSE if failed.
Example:
Memcache::connect usage
Instructions:
Open the memcached server connection, establish a connection to the memcached server, and open it with Memcache::connect The connection will be automatically closed after the script is executed. You can also use Memcache::close() to close the connection. The same function is memcache_connect().
Parameters:
$host: Points to the host of the link that memcached is listening to. This parameter will have another special connection method unix:///path/to/memcached.sock, which uses unix domain name sockets. , in this case, the port must be set to 0
$port: Point to the port of the link that memcached is listening to. In the case of unix domain name sockets, the port must be set to 0
$timeout: used to connect to the daemon Number of seconds for the process. When you change the default value of 1 second, you need to consider that if your connection is too slow, you may lose the advantages of caching.
Return value:
Return TRUE if successful, return FALSE if failed.
Example:
##memcache::debug
Description:
Control the debugging function, provided that the -enable-debug option is used when php is compiled, otherwise this function will not have any effect.
Parameters:
$on_off: true means turning on debugging, false means turning off debugging
Return value:
If php uses the -enable-debug option when compiling, return true, otherwise return false
Memcache::decrement usage
Description:
Memcache::decremen method is used to subtract the value in a saved key. Its usage is similar to Memcache::increment.
You can also use the memcache_decrement() function.
Parameters:
Key: The name of the key you want to reduce
Value: The value you want to reduce.
Return value:
If successful, return the reduced value, if failed, return false.
Example:
This example even demonstrates the Memcache::increment function.
Memcache::delete usage
Description:
Delete a key value. If the parameter $timeout is set, the stored value will expire after the set seconds. You can also use Function memcache_delete()
Return value:
Returns TRUE if successful, returns FALSE if failed.
Example:
##Memcache::flush
Description:
Clear all cached data. Memcache::flush does not actually release resources, it just marks all caches as expired, so that new caches can cover the occupied memory space. The same function is memcache_flush()
Return value:
Returns TRUE if successful, returns FALSE if failed.
Example:
Memcache::get
Explanation:
The function of the method is to obtain a key value. The key value can be an array, and the result will contain key-value pairs.
Parameters:
$key is the key value or an array value of a key.
$flags If this parameter exists, then $flags is related to the value written to this parameter. These $flags are similar to the $flags in the Memcache::set() function.
Return value:
If successful, return the value corresponding to the key, if failed, return false.
Example:
Memcache::getExtendedStats
## The code is as follows:
Description:
Get the running system statistics of all processes in the process pool. The same function is memcache_get_extended_stats()
Parameters:
$type indicates the type required to be returned: reset, malloc, maps, cachedump, slabs, items, sizes;
$slabid The first parameter is set to Used when using "cachedump".
$limit is used when the first parameter is set to "cachedump".
Return value:
If successful, statistical information will be returned. If failed, false will be returned.
Example:
Memcache::getServerStatus
Description:
Get the parameters for running the server. Returns the online or offline status of a server. The same function is memcache_get_server_status()
Parameters:
$host: The host of the listening connection
$port The port of the host of the listening connection, the default is 11211
Return value:
Successfully returns the server status. If the server is not started, 0 will be returned. Other numbers indicate that the server is started.
Example:
Memcache::getStats
Description:
Return some running statistics of the server. The same function is memcache_get_stats()
Parameters:
$type indicates the type required to be returned: reset, malloc, maps, cachedump, slabs, items, sizes;
$slabid The first parameter setting Used when "cachedump" is used.
$limit is used when the first parameter is set to "cachedump".
Memcache::getVersion
Description:
Return the version information of running Memcache. The same function memcache_get_version()
Return value:
Returns the version information of the server successfully, and returns false when it fails.
Example:
##Memcache::increment
## The code is as follows:
Perform addition operation on the value in a saved key
For usage, please refer to Memcache::decrement
Memcache::pconnect
The code is as follows:
Instructions:
Create a Memcache persistent connection object
The usage is similar to Memcache::connect(), the difference is that Memcache: :pconnect is a persistent connection established. This connection will not be closed after the script is executed or the Memcache::close() function is run. The function identical to it is memcache_pconnect()
Parameters:
$host: Points to the host of the link that memcached is listening to. This parameter will have another special connection method unix:///path/ to/memcached.sock, that is, use unix domain name sockets. In this case, the port must be set to 0
$port: Points to the port of the link that memcached is listening to. In the case of unix domain name sockets, the port must be set. Is 0
$timeout: The number of seconds used to connect to the daemon. When you change the default value of 1 second, you need to consider that if your connection is too slow, you may lose the advantage of caching.
Return value:
Return TRUE if successful, FALSE if failed
The code is as follows:
Memcache::replace
Description:
Overwrite an existing key. The same function is memcache_replace()
Parameters:
$key: The key value to be stored.
$var: The stored value, character type and integer type will be saved as the original value, other types will be automatically serialized and saved later.
$flag: Whether to use MEMCACHE_COMPRESSED to compress the stored value, true means compression, false means no compression.
$expire: The expiration time of the stored value. If it is 0, it means it will not expire. You can use a unix timestamp or description to represent the time from now, but when you use seconds to express it, it should not exceed 2592000 seconds. (meaning 30 days).
Return value:
Return TRUE if successful, return FALSE if failed. If the $key value already exists, FALSE will be returned.
Memcache::set
Description:
Add a value, if it already exists, overwrite it Write. The same function is memcache_set()
Parameters:
$key: The key value to be stored.
$var: The stored value, character type and integer type will be saved as the original value, other types will be automatically serialized and saved later.
$flag: Whether to use MEMCACHE_COMPRESSED to compress the stored value, true means compression, false means no compression.
$expire: The expiration time of the stored value. If it is 0, it means it will not expire. You can use a unix timestamp or description to represent the time from now, but when you use seconds to express it, it should not exceed 2592000 seconds. (meaning 30 days).
Return value:
Return TRUE if successful, return FALSE if failed.
Example:
Memcache::setCompressThreshold
Description:
Compress data 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 data size, and the second parameter represents the compression ratio. The default is 0.2.
Return value:
Return TRUE if successful, return FALSE if failed.
Example:
##Memcache::setServerParams
The code is as follows :
Modify the server parameters at runtime. The same function is memcache_set_server_params().
Parameters:
$host server address
$port server port
$timeout duration of connection
$retry_interval Interval time between connection retries, default is 15, set to -1 means no retry
$status controls the online status of the server
$failure_callback allows setting a callback function to handle error messages.
Return value:
Return TRUE if successful, return FALSE if failed.
Example:
The code is as follows:
6. Comprehensive usage examples
##If normal, The browser will output:
7. Example program code analysis
Initialize a Memcache object: $mem = new Memcache;
Connect to our Memcache server, the first one The parameter is the IP address of the server or the host name. 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 key of the data, used to locate a data, the second parameter is the data content that needs to be saved, here is a string, the third parameter is a mark, generally set to 0 or MEMCACHE_COMPRESSED. The fourth parameter is the validity period of the data, which means that the data is valid within this time. If this time has passed, the data will be cleared by the Memcache server. The unit is seconds. If it is set to 0, it will be valid forever. We set 60 here, which is the effective time of one minute: $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. Here is the key1 set in the previous step. Now after getting this data, output the output:
Now use the replace method to replace the value of key1 above. The parameters of the replace method are the same as those of set, but the first parameter key1 must be the key to replace the data content. The final output is:
Similarly, Memcache can also save arrays. The following is an array saved on Memcache, and then retrieved and output:
Now delete a data, use the delte interface, the parameter is a key, Then you can delete the key data of the Memcache server. There is no result in the final output:
Finally, we clear all the data saved on the Memcache server. We will find that the data is gone. Finally, the output key2 data is empty, and finally it is closed. Connection:
##When to use Memcache and Memcache usage environment
Websites that use Memcache generally have relatively large traffic. In order to relieve the pressure on the database, Memcache is used as a cache area to save part of the information in the memory, so that it can be quickly processed on the front end. for access. Then the general focus is on how to share database pressure and distribute it. After all, the memory capacity of a single Memcache is limited. I simply put forward my personal opinions here. I have not practiced them and should only be used as a reference.
Distributed Application
Memcache originally supports distributed, but our client has been slightly modified to provide better support. Our keys can be encapsulated appropriately and regularly. For example, for a user-based website, each user has a User ID, so it can be extracted and accessed according to a fixed ID. For example, users starting with 1 are stored in the On one Memcache server, the data of users starting with 2 is stored on the second Memcache server. The access data is first converted and accessed according to the User ID.
But this has the disadvantage that it requires judgment on the User ID. If the business is inconsistent, or other types of applications may not be so suitable, you can consider it based on your actual business, or think of a more suitable method.
Reduce database pressure
This is more important. All data are basically stored in the database. Every time the database is accessed frequently, the database will be damaged. The performance is extremely degraded and cannot serve more users at the same time. For example, MySQL locks the table very frequently, so let Memcache share the pressure on the database. We need a way to change the current architecture in a way that makes the changes relatively small and does not require large-scale changes to the front end.
A simple method I am considering:
The back-end database operation module extracts all Select operations (regardless of update/delete/insert), and then performs the corresponding hash algorithm on the corresponding SQL to calculate a Hash the data key (such as MD5 or SHA), and then use this key to find the data in Memcache. If the data does not exist, it means that it has not been written to the cache, then extract the data from the database, one is in array class format, and then Set the data into Memcache, the key is the hash value of the SQL, and then set an expiration time accordingly, such as one hour, then the data in one hour will be extracted from the cache, effectively reducing the pressure on the database. The disadvantage is that the data is not real-time. When the data is modified, it cannot be displayed on the front end in real time, and it may also occupy a large amount of memory. After all, the amount of data selected each time may be huge. This is a factor that needs to be considered.
Memcache security
Our Memcache server above operates directly after connecting to the client without any verification process, so if the server is directly exposed It is more dangerous on the Internet. At the least, the data is leaked and viewed by other unrelated people. At worst, the server is invaded, because Mecache runs with root privileges, and there may be some unknown bugs or buffer overflows in it. These are unknown to us, so the dangers are foreseeable. For the sake of security, I would like to make two suggestions to prevent hacker intrusion or data leakage.
Intranet access
It is best to make the access between the two servers in the form of an intranet, usually between the Web server and the Memcache server. Common servers have two network cards, one pointing to the Internet and one pointing to the intranet. Then let the web server access the Memcache server through the intranet network card. When our Memcache server is started, it monitors the IP address and IP address of the intranet. Ports and intranet access can effectively prevent other illegal access.
The Memcache server is set to listen to the 11211 port of the 192.168.0.200 IP on the intranet, occupying 1024MB of memory, and allowing a maximum of 1024 concurrent connections.
Set up the firewall
The firewall is a simple and effective way. If both servers are connected to the Internet and you need to access Memcache through the external IP, then you can Consider using a firewall or proxy to filter unauthorized access. Generally, under Linux, we can use iptables or ipfw under FreeBSD to specify some rules to prevent some illegal access. For example, we can set up to only allow our web server to access our Memcache server, while blocking other access.
The above iptables rule only allows the 192.168.0.2 web server to access the Memcache server , which can effectively prevent some illegal access. Correspondingly, you can also add some other rules to strengthen security. This can be done according to your own needs.
##Actual combat
//memcached configuration/******************************************* */
$mem_ip='127.0.0.1';
$mem_port=11211;
$mem_prefix='';
/********************************************/
//session memcached configuration, please configure it to an independent memcache service (different IP or different port number),
//Several mirror stations must be set the same, otherwise it will cause session Lost
//No other program can use this service to avoid conflicts.
/********************************************/
$session_mem_ip='127.0.0.1';
$session_mem_port=11212;
{
static $mem=false;
if($mem==false && isset($GLOBALS['mem_ip']) && isset($GLOBALS['mem_port']) && extension_loaded('memcache'))
{
$mem=new Memcache;
$mem->pconnect($GLOBALS['mem_ip'],$GLOBALS['mem_port']) or die('Can not connect to memcache server! ');
}
return $mem;
}
The above is the detailed content of Introduction to memcache. For more information, please follow other related articles on the PHP Chinese website!