PHP memory cache memcached module installation and usage

Source: Internet
Author: User
Tags php memcached
PHP memory cache memcached module installation and usage

  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 to run the memcached daemon. you only need to run the memcached daemon with one command line. you do not need to modify any configuration file (or modify the configuration file ): /usr/bin/memcached-d-m 128-l 192.168.1.1-p 11211-u httpd parameter explanation:-d runs memcached in daemon mode; -m: Set the memory size that memcached can use. the unit is M.-l: Set the IP address of the listener. if it is a local machine, this parameter is usually not set; -p is used to set the listening port. the default value is 11211. Therefore, you can leave this parameter unspecified.-u specifies the user. if the current value is root, you must use this parameter to specify the user. Of course, there are other parameters that can be used. man memcached can be seen at a moment.

III. working principle of memcached first, memcached runs on one or more servers as a daemon and accepts client connection operations at any time. the client can be written in various languages, currently, known client APIs include Perl, PHP, Python, Ruby, Java, C #, and C. After the PHP client establishes a connection with the memcached service, the next thing is to access the object. each accessed object has a unique identifier key, and the access operation is performed through this key, objects saved to memcached are actually stored in the memory, not in the cache file. This is why memcached is so efficient and fast.

Note that these objects are not persistent. after the service is stopped, the data in the objects will be lost.

4. there are two ways to use PHP as the memcached client:

PHP can be used as the memcached client to call the memcached service for object access.

First, PHP has an extension called memcache. during compilation in Linux, The-enable-memcache [= DIR] option must be included, and the Window is in php. remove the annotator in front of php_memcache.dll in ini to make it available. In addition, there is also a way to avoid the trouble of extension and re-compilation, that is, directly using php-memcached-client.

The second method is used in this article. although the efficiency is slightly lower than that of the extended library, it is not a problem. 4. PHP memcached application example first download the memcached-client.php, after downloading the memcached-client.php, you can operate the memcached service through the class "memcached" in this file. In fact, code calls are very simple. The main methods used are add (), get (), replace (), and delete (). The methods are described as follows: add ($ key, $ val, $ exp = 0) writes an object to memcached. $ key is the unique identifier of the object. $ val is the data of the written object. $ exp is the expiration time, in seconds, the default value is unlimited. get ($ key) obtains the object data from memcached and obtains the data through the unique identifier $ key of the object. replace ($ key, $ value, $ exp = 0) use $ value to replace the content of an object with $ key in memcached. the parameter works only when the $ key object exists like the add () method. delete ($ key, $ time = 0) delete the $ key object in memcached. $ time is an optional parameter, indicating how long it takes to wait before the deletion.

The following is a simple test code that allows you to access the object data with the identifier 'MyKey:

  1. // Contains the memcached class file
  2. Require_once ('memcached-client. php ');
  3. // Option settings
  4. $ Options = array (
  5. 'Servers' => array ('192. 168.1.1: 100'), // address and port of the memcached service. multiple array elements can be used to represent multiple memcached services.
  6. 'Debug' => true, // whether to enable debug
  7. 'Compress _ threshold '=> 10240, // when the number of bytes of data exceeds
  8. 'Persistant' => false // whether to use persistent connection
  9. );
  10. // Create a memcached object instance
  11. $ Mc = new memcached ($ options );
  12. // Set the unique identifier used by this script
  13. $ Key = 'MyKey ';
  14. // Write an object to memcached
  15. $ Mc-> add ($ key, 'some random string ');
  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' => 'hahaha', 'array' => 'XXX '));
  21. $ Val = $ mc-> get ($ key );
  22. Echo "n". str_pad ('$ mc-> replace ()', 60, '_'). "n ";
  23. Var_dump ($ val );
  24. // Delete an object 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. ?>

In practical applications, the database query result set is usually saved to memcached. The result set is directly obtained from memcached during the next visit, instead of performing database query operations, this can greatly reduce the burden on the database. Generally, the value after the md5 () of the SQL statement is used as the unique identifier key.

The following is an example of using memcached to cache the database query result set (this code snippet is followed by the preceding sample code ):

  1. $ SQL = 'select * FROM users ';
  2. $ Key = md5 ($ SQL); // memcached object identifier
  3. {
  4. // If no cached data is obtained in memcached, use database query to obtain the record set.
  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 for the next access.
  12. $ Mc-> add ($ key, $ datas );
  13. {
  14. Echo "n". str_pad ('read datas from memcached. ', 60,' _ '). "n ";
  15. }
  16. Var_dump ($ datas );
  17. ?>

It can be seen that after memcached is used, the database connection and query operations can be reduced, the database load is reduced, and the script running speed is also improved. I have previously written an article titled "PHP achieves multi-server sharing SESSION data". the SESSION in this article is saved in a database. when the concurrency traffic is high, the server load is very large and often exceeds the maximum number of connections in MySQL. using memcached, we can solve this problem well. The working principle is as follows: when a user accesses a webpage, check whether the current user's SESSION data exists in memcached and use session_id () as the unique identifier. if the data exists, it will be returned directly. if the data does not exist, connect to the database to obtain SESSION data, save the data to memcached for the next use. when the current PHP run ends (or session_write_close () is used), the My_Sess: write () method is called, write data to the database. in this way, database operations are still performed each 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 the data with the SESSION data to be written in the write () method, different databases are connected and written to the database. at the same time, the corresponding objects in memcached are deleted. if they are the same, the SESSION data is not changed, so no operation can be performed and the data is returned directly;

So how can we solve the user's SESSION expiration time? Do you remember that the add () method of memcached has an expiration time parameter $ exp? Set this parameter to a value smaller than the maximum SESSION survival time. In addition, do not forget to extend the SESSION duration for those users who have been online. this can be solved in the write () method. by judging the time, the database data will be updated if the conditions are met.

Memcached client of php

Before installing memcache, we mentioned that the memcached client is called memcache. In fact, another client based on libmemcached is memcached. it is said that memcached has better performance and more functions.

Official memcache homepage: Alibaba

The following is a process record for installing the PHP module of the Memcached version:

  1. $ Mem = new Memcache;

  2. $ Mem-> addServer ($ memcachehost, '20140901 ');
  3. $ Mem-> addServer ($ memcachehost, '20140901 ');
  4. $ Mem-> set ('hx ', '9enjoy ');
  5. Echo $ mem-> get ('hx ');

  6. $ Md = new Memcached;

  7. $ Servers = array (
  8. Array ($ memcachehost, '20140901 '),
  9. Array ($ memcachehost, '20140901 ')
  10. );
  11. $ Md-> addServers ($ servers );
  12. $ Md-> set ('hx ', '9enjoy ');
  13. Echo $ md-> get ('hx ');

Memcached has more methods than memcache, such as getMulti, getByKey, and addServers. Memcached does not have the connect method of memcache, and does not support persistent connections at present. Memcached supports Binary Protocol, but memcache does not, which means memcached has higher performance. Memcache is native and supports both OO and non-OO interfaces. memcached uses libmemcached and only supports OO interfaces. More detailed difference: http://code.google.com/p/memcached/wiki/PHPClientComparison

The memcached server is a centralized cache system, and the distributed implementation method is determined by the client. The memcached distribution algorithm generally has two options: 1. based on the hash (key) result, the remainder of the number of modulo connections determines the node to store, that is, hash (key) % sessions. size (). This algorithm is simple and fast and performs well. However, this algorithm has a disadvantage: When a memcached node is added or deleted, the original cache data will expire on a large scale, and the hit rate will be greatly affected. if the number of nodes is large and the cache data is large, rebuilding the cache is too costly, so there is a second algorithm. 2. Consistent Hashing: Consistent Hash Algorithm. the process of searching nodes is as follows:

First, obtain the hash value of the memcached server (node) and configure it to 0 ~ 232 of the circle (continuum. Then, use the same method to obtain the hash value of the key for storing the data and map it to the circle. Search clockwise from the location where the data is mapped, and save the data to the first server. If the server cannot be found after the power of 2 is 32, it will be saved to the first memcached server.

Memcache uses the first method without any configuration. Memcached implements the first method, which seems to be used (unconfirmed): $ md-> setOption (Memcached: OPT_HASH, Memcached: HASH_CRC );

The second consistent hash algorithm: memcache in php. ini

Memcache. hash_strategy = consistent Memcache. hash_function = crc32

Memcached is added in the program (unconfirmed)

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

Related Article

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.