📜 ⬆️ ⬇️

Memcached and PHP educational program

There is a lot of information on this topic on the Internet, but despite this, many bypass it. The purpose of this post, explain on the fingers the basics of interaction with Memcached.

What is Memcache and how does it relate to PHP?


Memcache is designed for caching data, the generation of which requires a large amount of resources. This kind of data can contain anything, starting with the results of a database query and ending with a heavy piece of the template. Memcached is not included in the basic set of modules shipped with PHP, however it is available in the pecl repository.

Installation and Setup


As the distribution in question, I decided to use Debian, because it is most often used when creating web servers. Memcached module for PHP is available in the repository already compiled (php5-memcached), but I will describe the installation process from the source code, since not all repositories are as rich as Debian's.

Install Memcached Server


# apt-get install memcached
For a start, the next config is enough for you:
# / etc / memcached.conf
#Memcached will work as a daemon
-d
# Log will add there
logfile / var / log / memcached.log
# Let's allocate 256 megabytes of RAM for storage
-m 256
# This port will listen
-p 11211
# Later it is desirable to change
-u nobody
# Listen to localhost
-l 127.0.0.1

# / etc / init.d / memcached restart
')
Check

# netstat -tap | grep memcached
tcp 0 0 localhost: 11211 * : * LISTEN 13036 / memcached

Compile and install the module for PHP


apt-get install php5-dev libmemcache-dev

pecl download memcache
tar xzvf memcache-2.2.6.tgz
cd memcache-2.2.6 /
phpize && . / configure --enable-memcache && make
cp modules / memcache.so / usr / lib / php5 / 20060613 /

echo 'extension = memcache.so' >> / etc / php5 / apache2 / php.ini
/ etc / init.d / apache2 restart

That's all! Not at all difficult.

Examples of using


1. Basic operations


  1. <? php
  2. // Create a new object. You can also write in procedural style.
  3. $ memcache_obj = new Memcache ;
  4. // Connect to our server
  5. $ memcache_obj -> connect ( '127.0.0.1' , 11211 ) or die ( "Could not connect" ) ;
  6. // Try to get an object with our_var key
  7. $ var_key = @ $ memcache_obj -> get ( 'our_var' ) ;
  8. if ( ! empty ( $ var_key ) )
  9. {
  10. // If the object is cached, output its value.
  11. echo $ var_key ;
  12. }
  13. else
  14. {
  15. // If there is no object with the key our_var in the cache, create it
  16. // Our_var object will be stored for 5 seconds and will not be compressed
  17. $ memcache_obj -> set ( 'our_var' , date ( 'G: i: s' ) , false , 5 ) ;
  18. // Print the cached data
  19. echo $ memcache_obj -> get ( 'our_var' ) ;
  20. }
  21. // Close the connection to the Memcached server
  22. $ memcache_obj -> close ( ) ;
  23. ?>

As a result of executing this code, time will be displayed each time with an accuracy of seconds. However, it will be updated every 5 seconds until the cache is cleared. In this example, the simplest operations are illustrated, but in performance we will lose rather than win. After all, every time we have to connect to the server ...

2. Increase productivity



2.1 With caching

  1. < ? php
  2. function LoadCPU ( )
  3. {
  4. // The function that should load the processor
  5. // Create 800x600 Image
  6. $ image = imagecreate ( 800 , 600 ) ;
  7. // White background color
  8. $ color = imagecolorallocate ( $ image, 255 , 255 , 255 ) ;
  9. //The black
  10. $ color2 = imagecolorallocate ( $ image, 0 , 0 , 0 ) ;
  11. for ( $ i = 0 ; $ i < 10000 ; $ i ++ ) {
  12. // Place 10,000 dots in random order
  13. imagesetpixel ( $ image, rand ( 0 , 800 ) , rand ( 0 , 600 ) , $ color2 ) ;
  14. }
  15. // Throw A Pointer
  16. return $ image ;
  17. }
  18. // Create a new Memcache object
  19. $ memcache_obj = new Memcache ;
  20. // Connect to our server
  21. $ memcache_obj - > connect ( '127.0.0.1' , 11211 ) or die ( "Could not connect" ) ;
  22. // Try to get the object with the key image
  23. $ image_bin = @ $ memcache_obj - > get ( 'image' ) ;
  24. if ( empty ( $ image_bin ) ) {
  25. // If there is no image in the cache, generate it and cache it
  26. imagepng ( LoadCPU ( ) , getcwd ( ) . '/tmp.png' , 9 ) ;
  27. $ image_bin = file_get_contents ( getcwd ( ) . '/tmp.png' ) ;
  28. unlink ( getcwd ( ) . '/tmp.png' ) ;
  29. $ memcache_obj - > set ( 'image' , $ image_bin, false , 30 ) ;
  30. }
  31. // Get the image out of the cache
  32. header ( 'Content-type: image / png' ) ;
  33. echo $ image_bin ;
  34. // Close the connection to the Memcached server
  35. $ memcache_obj - > close ( ) ;
  36. ? >

In this example, there is a function that creates an image of 800x600 in size and places 10,000 dots on it. Once, having generated such an image, in the future we only display it on the screen, without generating it anew.

2.2 Without caching

  1. <? php
  2. function LoadCPU ( )
  3. {
  4. // The function that should load the processor
  5. // Create 800x600 Image
  6. $ image = imagecreate ( 800 , 600 ) ;
  7. // White background color
  8. $ color = imagecolorallocate ( $ image , 255 , 255 , 255 ) ;
  9. //The black
  10. $ color2 = imagecolorallocate ( $ image , 0 , 0 , 0 ) ;
  11. for ( $ i = 0 ; $ i < 10000 ; $ i ++ ) {
  12. // Place 10,000 dots in random order
  13. imagesetpixel ( $ image , rand ( 0 , 800 ) , rand ( 0 , 600 ) , $ color2 ) ;
  14. }
  15. // Throw A Pointer
  16. return $ image ;
  17. }
  18. // Display the image without caching
  19. header ( 'Content-type: image / png' ) ;
  20. imagepng ( LoadCPU ( ) , '' , 9 ) ;
  21. ?>

Everything is much simpler and more familiar here: we generate an image every time.

results

I tested both scripts for performance. The same machine in the first case gave 460 responses per second, and in the second only 10. That was to be expected.
memcache


Some more useful features.



addServer - in case you have several caching servers at your disposal, you can create a cluster by adding servers to the pool. Pay attention to the weight parameter. It indicates how much memory you will have available on a particular server.
delete - it is clear from the name that this method deletes an object with a given key from the cache.
replace - replaces the value of the object with the specified key. Use in case you need to change the contents of an object before it expires.

Total


From my point of view, it is necessary to apply caching only on high-loaded resources. After all, every time you connect to the Memcached server, you are wasting precious time, which most likely will not be justified. As for large projects, it is better to immediately write more lines of code than to do it in trouble, with the idea that your service is lying. Also do not forget about the use of memory! Note that putting 300 megabytes in the cache, you have taken away 300 megabytes of RAM ...
In conclusion, I want to say that this article does not reveal all the delights of technology, but I hope that it stimulates you to self-improvement. Thanks for reading, dear% username%!

UPD: Another interesting point. Memcached, there is a PHP API to libmemcached. And Memcache, a php library that does not use libmemcached.

Source: https://habr.com/ru/post/108274/


All Articles