PHP memory cache memcached module installation and usage

WBOY
Release: 2016-07-25 08:52:43
Original
792 people have browsed it
  1. # tar -xzf libevent-1.1a.tar.gz
  2. # cd libevent-1.1a
  3. # ./configure --prefix=/usr
  4. # make
  5. # make install
  6. # cd ..
  7. # tar -xzf memcached-1.1.12.tar.gz
  8. # cd memcached-1.1.12
  9. # ./configure --prefix=/usr
  10. # make
  11. # make install
复制代码

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':

  1. // Contains memcached class files
  2. require_once('memcached-client.php');
  3. // Options settings
  4. $options = array(
  5. 'servers' => array('192.168.1.1:11211 '), //The address and port of the memcached service, multiple array elements can be used to represent multiple memcached services
  6. 'debug' => true, //Whether debug is turned on
  7. 'compress_threshold' => 10240, //How many words are exceeded Compress the data in the section
  8. 'persistant' => false //Whether to use persistent connections
  9. );
  10. //Create a memcached object instance
  11. $mc = new memcached($options);
  12. //Set the unique value used by this script Identifier
  13. $key = 'mykey';
  14. // Write object to memcached
  15. $mc->add($key, 'some random strings');
  16. $val = $mc->get($key );
  17. echo "n".str_pad('$mc->add() ', 60, '_')."n";
  18. var_dump($val);
  19. // Replace the written object data value
  20. $mc->replace($key, array('some'=>'haha', 'array'=>'xxx'));
  21. $val = $mc->get($key);
  22. echo "n".str_pad('$mc->replace() ', 60, '_')."n";
  23. var_dump($val);
  24. // Delete objects in memcached
  25. $mc-> ;delete($key);
  26. $val = $mc->get($key);
  27. echo "n".str_pad('$mc->delete() ', 60, '_')."n ";
  28. var_dump($val);
  29. ?>
Copy code

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):

  1. $sql = 'SELECT * FROM users';
  2. $key = md5($sql); //memcached object identifier
  3. {
  4. //If cached data is not obtained in memcached, use database query Get the recordset.
  5. echo "n".str_pad('Read datas from MySQL.', 60, '_')."n";
  6. $conn = mysql_connect('localhost', 'test', 'test');
  7. mysql_select_db(' test');
  8. $result = mysql_query($sql);
  9. while ($row = mysql_fetch_object($result))
  10. $datas[] = $row;
  11. // Save the result set data obtained from the database to memcached in for your next visit.
  12. $mc->add($key, $datas);
  13. {
  14. echo "n".str_pad('Read datas from memcached.', 60, '_')."n";
  15. }
  16. var_dump($ datas);
  17. ?>
Copy the code

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:

  1. $mem = new Memcache;

  2. $mem->addServer($memcachehost, '11211');
  3. $mem->addServer($memcachehost, '11212');
  4. $mem->set('hx','9enjoy');
  5. echo $mem->get('hx');

  6. $md = new Memcached;

  7. $servers = array(
  8. array($memcachehost, '11211'),
  9. array($memcachehost, '11212')
  10. );
  11. $md->addServers($servers);
  12. $md->set('hx', '9enjoy');
  13. echo $md->get('hx');

Copy code

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 =crc32

memcached 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);


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!