Home > Article > Backend Development > PHP memory cache memcached module installation and usage
After the installation is complete, memcached should be in /usr/bin/memcached. 3. Run the memcached daemon. Running the memcached daemon is very simple. It only requires a command line. There is no need to modify any configuration files (there is no configuration file for you to modify): /usr/bin/memcached -d -m 128 -l 192.168.1.1 -p 11211 -u httpd parameter explanation: -d runs memcached in daemon mode; -m sets the memory size that memcached can use, in M; -l sets the monitoring IP address. If it is the local machine, this parameter usually does not need to be set; -p sets the listening port, the default is 11211, so this parameter does not need to be set; -u specifies the user. If you are currently root, you need to use this parameter to specify the user. Of course, there are other parameters that can be used. You can see them by running man memcached. 3. The working principle of memcached: First, memcached runs in one or more servers as a daemon and accepts client connection operations at any time. Clients can be written in various languages. Currently known client APIs include Perl/PHP /Python/Ruby/Java/C#/C etc. After clients such as PHP establish a connection with the memcached service, the next thing is to access objects. Each accessed object has a unique identifier key. Access operations are performed through this key and saved to memcached. The objects in are actually placed in memory, not stored in cache files, which is why memcached can be so efficient and fast. Note that these objects are not persistent, and the data inside will be lost after the service is stopped. 4. How to use PHP as a memcached client? There are two methods You can use PHP as a memcached client to call the memcached service for object access operations. First, PHP has an extension called memcache. When compiling under Linux, you need to bring the –enable-memcache[=DIR] option. Under Windows, remove the comment in front of php_memcache.dll in php.ini to make it available. . In addition, there is another way to avoid the trouble caused by expansion and recompilation, which is to use php-memcached-client directly. This article uses the second method. Although the efficiency will be slightly worse than the extension library, it is not a big problem. 4. PHP memcached application example First download memcached-client.php. After downloading memcached-client.php, you can operate the memcached service through the class "memcached" in this file. In fact, the code call is very simple. The main methods used are add(), get(), replace() and delete(). The method description is as follows: add ($key, $val, $exp = 0) Write objects to memcached. $key is the unique identifier of the object. $val is the written object data. $exp is the expiration time in seconds. The default is unlimited time; get ($key) Obtain object data from memcached through the object's unique identifier $key; replace ($key, $value, $exp=0) Use $value to replace the object content with the identifier $key in memcached. The parameters are the same as the add() method. It will only work if the $key object exists; delete ($key, $time = 0) Delete the object with the identifier $key in memcached. $time is an optional parameter, indicating how long to wait before deleting. The following is a simple test code that accesses object data with the identifier 'mykey':
In practical applications, the result set of the database query is usually saved in memcached, and the next time it is accessed, it is obtained directly from memcached instead of doing the database query operation. This can reduce the burden on the database to a great extent. Usually the value after the SQL statement md5() is used as the unique identifier key. The following is an example of using memcached to cache a database query result set (this code snippet follows the sample code above):
It can be seen that after using memcached, database connections and query operations can be reduced, the database load is reduced, and the running speed of the script is also improved. I have written an article before called "PHP implements multi-server sharing of SESSION data". The SESSION in the article is saved in a database. When the number of concurrent visits is large, the load on the server will be very large, often exceeding the maximum connection of MySQL. Number, using memcached, we can solve this problem well. The working principle is as follows: When the user accesses the web page, check whether there is the SESSION data of the current user in memcached, and use session_id() as the unique identifier; if the data exists, it will be returned directly. If it does not exist, connect to the database again, obtain the SESSION data, and use this data. Save to memcached for next time use; When the current PHP operation ends (or session_write_close() is used), the My_Sess::write() method will be called to write the data to the database. In this case, there will still be database operations every time. This method also needs to be optimized. . Use a global variable to record the SESSION data when the user enters the page, and then compare this data in the write() method to see if it is the same as the SESSION data you want to write. If they are different, connect to the database and write it to the database, and at the same time, add the corresponding data in memcached. Objects are deleted. If they are the same, it means that the SESSION data has not changed, so you can return directly without doing any operation; So how to solve the user SESSION expiration time? Remember that memcached’s add() method has an expiration time parameter $exp? Just set this parameter value to be less than the maximum survival time of SESSION. In addition, don’t forget to extend the SESSION duration for those users who are always online. This can be solved in the write() method. By judging the time, the database data will be updated if the conditions are met. php memcached client memcached When I installed memcache, I mentioned that the memcached client is called memcache. In fact, there is a client based on libmemcached called memcached, which is said to have better performance and more functions. memcache’s official homepage: http://pecl.php.net/package/memcache The official homepage of memcached: http://pecl.php.net/package/memcached The following is the process record of installing the Memcached version of the PHP module:
memcached has many more methods than memcache, such as getMulti, getByKey, addServers, etc. Memcached does not have the connect method of memcache, and it does not currently support long connections. Memcached supports Binary Protocol, but memcache does not, which means memcached will have higher performance. Memcache is implemented natively and supports the coexistence of both OO and non-OO interfaces. Memcached uses libmemcached and only supports OO interfaces. More detailed differences: http://code.google.com/p/memcached/wiki/PHPClientComparison The memcached server is a centralized caching system, and the distributed implementation method is determined by the client. There are generally two options for memcached's distribution algorithm: 1. According to the result of hash(key), the remainder of the modular connection number determines which node to store, that is, hash(key)% sessions.size(). This algorithm is simple, fast, and performs well. However, this algorithm has a shortcoming, that is, when memcached nodes are added or deleted, the original cached data will become invalid on a large scale, and the hit rate will be greatly affected. If there are many nodes and cached data, the cost of rebuilding the cache will be too high, so With the second algorithm. 2. Consistent Hashing, consistent hashing algorithm, its node search process is as follows: First find the hash value of the memcached server (node) and configure it on the circle (continuum) from 0 to 232. Then use the same method to find the hash value of the key storing the data and map it to the circle. It then searches clockwise starting from the location where the data is mapped, and saves the data to the first server found. If the server is still not found after exceeding 2 to the power of 32, it will be saved to the first memcached server. Memcache uses the first method without any configuration. To implement the first method, memcached seems to use (unconfirmed): $md->setOption(Memcached::OPT_HASH, Memcached::HASH_CRC); The second consistent hashing algorithm: memcache is added in php.ini Memcache.hash_strategy =consistent Memcache.hash_function =crc32memcached is added to the program (not confirmed) $md->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT); $md->setOption(Memcached::OPT_HASH, Memcached::HASH_CRC); or $mem->setOption(Memcached::OPT_DISTRIBUTION,Memcached::DISTRIBUTION_CONSISTENT); $mem->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE,true); |