Php memcached examples. Memcached: installation and configuration. Installation and configuration

Today we will deal with an interesting data caching mechanism: Memcache php. The great thing about memcahe is that we can cache anything, from SQL queries to objects and any other data structures.

What is Memcache

Memcache- This is not a simple caching technology or algorithm; first of all, it is a server program running on a web server. If you use hosting services, then before using memcahe in your application, you need to make sure that memcahe is available. This can be done using the phpinfo() function.

Concept

After making sure that the memcahe server is available for use, let's get acquainted with the concept of this caching mechanism. The most attractive thing about using memcahe php is that all cached data is stored in the server's RAM. This principle of data storage not only saves processor time on forming it again and again, but also greatly increases the speed of access to it.

In a simplified version, the concept of memcahe can be stated as follows: frequently used PHP objects are cached and stored in the server RAM as a set of key-object pairs; if necessary, previously saved objects are taken from the server memory, bypassing numerous connections to the database checks and cycles. In the case when the memcahe php algorithm does not detect the requested object in memory, the required object is created in the usual way and stored in the cache.

How to work with Memcache server in PHP

To work with the Memcache server, we need one of the PHP libraries php-memcache or php-memcached.

The choice of one library or another depends on the individual needs of the developer; for the most part, they are very similar to each other, with the difference that php-memcached provides several great opportunities for work such as:

  • CAS tokens for key versioning
  • Callbacks
  • The getDelayed() method allows you to reduce wait time by delaying the actual reading of keys
  • Binary protocol support
  • Ability to avoid serialization using igbinary

Both modules php-memcach And php-memcached, are not standard for php, but are available in the PECL repository.

If you work not on your own server, but on a hosting server, you won’t have to choose, everything will be already configured.

Example of work

Let me immediately draw your attention to the fact that this example will work equally well on php-memcach and php-memcached.

Memcach php uses the following methods to work with data:

  1. get - to get an object from the cache;
  2. set — writing an object by key to the cache;
  3. add — writing an object to the cache if it does not already have such a key;
  4. replace — writing an object to the cache if the key already exists.

I will give a primitive example of using caching using the memcache server.

1
2
3
4
5
6
7

$memcache = new Memcache() ;
$memcache -> pconnect ("localhost" , 3211 ) ; //Connect. By default, any port can be used
$key = "key_1" ;
$value = array (1, 2, 3, 4, 5);
$expire = 600 ;
$memcache -> set ($key , $value , 0 , $expire ) ; // Save the value for 10 minutes
$memcache -> get ("key_1" ) ; // get the previously written array

When using a memcache server for several projects at once, remember that the data is written to one RAM. This means that if you write new values ​​using the same key from different projects, the last value that entered memory will be available for both.

This article is in the nature of “First Aid”. A detailed description of specific actions that allow you to install and configure memcached on the server.

Let's start with a definition.

Memcached- software that implements a data caching service in RAM based on a hash table.

Initial data:

  • VPS running on an operating system Debian;
  • a valid website that can be accessed via FTP, SSH.

Let's start with the last point. Thanks to a running Internet resource (or something similar), we can quickly and easily find out what we have installed (perhaps we will find memcached, among other things). Let's create a file called info.php in which we will write:

Let's run the code by going to http://example.com/info.php:

If, among everything else, you find a similar entry, then everything is in order and the job has already been done. Otherwise, we will get this result based on the actions described in this publication.

Installing the Memcached server

Let's start the installation with the command

Apt-get install memcached php5-memcache

We are waiting for the installation to complete. Then we will check the results with the command netstat

As a result we get:

Tcp 0 0 *:11211 *:* LISTEN 13053/memcached

As we can see, by default memcached “listens” to port 11211. Therefore, through this port anyone can connect and use our memcached server. Let's protect ourselves by giving this right only to our server (localhost). Open the /etc/memcached.conf file through the control panel or through the console:

Vi /etc/memcached.conf

This file contains detailed comments. Be sure to check them out.

Add the line -l 127.0.0.1 .

Reboot the memcached server with the command:

/etc/init.d/memcached restart

And let's check again:

Netstat -tap | grep memcached

As a result we should get something like

Tcp 0 0 localhost.localdo:11211 *:* LISTEN 13092/memcached

Now memcached only works on the local server.

Installing memcache

List of commands (memcache version may differ!):

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

Restart Apache:

Apachectl graceful

Let's check the script we posted earlier at http://example.com/info.php. Now we should find the Memcache item there.

Let's check the operation of Memcached

Let's create a result.php file and run it.

connect("localhost", 11211) or exit("Unable to connect to the Memcached server"); $version = $memcache->getVersion(); echo "Server"s version: ".$version."
\n"; $tmp_object = new stdClass; $tmp_object->str_attr = "test"; $tmp_object->int_attr = 123; $memcache->set("key", $tmp_object, false, 10) or die ("Not I managed to leave an entry in Memcached"); echo "We write data to the Memcached cache (data will be stored for 10 seconds)
\n"; $get_result = $memcache->get("key"); echo "Data written to Memcached:
\n"; var_dump($get_result); ?>

The result of the script:

Server's version: 1.4.13 Write data to the Memcached cache (data will be stored for 10 seconds) Data written to Memcached: object(stdClass)#3 (2) ( ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) )

Is everything like this or almost like this? Then everything is fine. If not, try repeating the procedures.

Article for beginners. Memcached is a thing for caching data in the server's RAM.

What's the point? The site usually takes data from the database, and the database is a large file on disk, and reading from disk is a priori slower than from memory. This does not begin to appear immediately - as soon as the attendance exceeds several tens of thousands of people, and the tables in the database grow to hundreds of thousands of rows. Moreover, the database itself is by definition inefficient. Let's say we store 1,000,000 posts in the database, but over the past few days, 95% of all views are only 100 posts. But every time we have to go into a huge database file and look for several frequently requested records in it - and this increases the load on the server and the time it takes to open the site. If we put these entries in the cache, then we will speed up the site and there is no need to buy powerful servers. In a word, cash is profit!

Caching comes in different forms. The simplest thing is caching on . The downside is that the data is still stored on disk, and this can lead to dire consequences. You can cache intermediate results in the database (for example, search results in some forum engines are stored in the database). Well, the most effective thing is, of course, storage in RAM. There are a bunch of third-party programs for this: Memcached, eAccelerator, APC, XCache. By the way, MySQL can also store data in its cache (we are not talking about indexes in memory).

In general, they write that eAccelerator and XCache are more efficient than Memcached if you use one server, since in the case of Memcached you need to open a TCP connection. But Memcached has the main advantage - the ability to distribute data across several servers. For example, the LiveJournal cache will not fit into the memory of even the most powerful server. Actually, Memcached was invented for LiveJournal so that data could be stored on several servers. But for us beginners, it’s too early to think about it.

Features of Memcached

  • Simple data storage structure (key-value).
  • The maximum cache lifetime is 30 days.
  • The maximum volume of one element is 1 Mb
  • You can store objects and arrays as is. When caching in files or in the database, such things need to be put into a string using serialization before saving.
  • No authorization (password-login). Those. if the server has Memcached, then any user on the same server can access it.
  • The speed of data access does not depend on the number of elements in the cache. Yes Yes exactly.

Installation

There are a lot of installation instructions on the net, whether on Unix or Windows. In addition to Memcached itself, you also need to install a lib for accessing Memcached via PHP (by analogy with the MySQL database - in addition to the database itself, you also need to install the mysql or mysqli extension).

But the easiest way is to write to the hoster. On fastvps, when ordering a server, Memcached is installed by default. The main thing is to indicate how much memory needs to be allocated for the cache. By default it is 67 Mb. I have 4 Gb of RAM, so I can safely allocate 1 Gb. In general, the easiest way to estimate how much memory is needed for a cache is to multiply the size of the database by 2. For example, the databases on all our sites weigh 300 MB, then we allocate 600 MB for the cache, or it is better to take 1 GB, with a margin.

Memcached can be seen in phpinfo

Examination

Usually Memcached runs on localhost and is accessible via port 11211
Let's look at the statistics

connect("localhost",11211); print_r($memcache->getStats()); ?>

Result:
Array
=> 5915
=> 583
=> 1309538445
=> 1.2.2
=> 64
=> 0.000000
=> 0.004000
=> 0
=> 0
=> 0
=> 1
=> 2
=> 2
=> 0
=> 0
=> 0
=> 0
=> 0
=> 7
=> 0
=> 1073741824
=> 1
)

After some time the statistics will look something like this

Array
=> 5915
=> 6202245
=> 1315740107
=> 1.2.2
=> 64
=> 3.464216
=> 10.868679
=> 298
=> 17728
=> 120366
=> 1
=> 28654
=> 4
=> 133296
=> 17728
=> 124758
=> 8538
=> 0
=> 11125692
=> 103815319
=> 1073741824
=> 1
)

Basic parameters:
=> 298 - how many current elements are in the cache.
=> 17728 - how many total elements were in the cache (including deleted ones)
=> 120366 - how many bytes are currently in the cache
=>1073741824 - how many bytes are generally available for the cache (here 1 Gb)
=> 124758 - how many times we took data from the cache
=> 8538 - how many times we tried to take data from the cache, but it was not there or the cache lifetime expired.

The get_misses/get_hits ratio shows the efficiency of cache usage. The smaller it is, the more efficiently the cache is used. In this case, we get that 93% of the data is taken from the cache. If you get_misses/get_hits=1, then you are doing something wrong (most likely you are setting the cache lifetime too low).

visual statistics
The code above displays statistics in a dry form like print_r()
There is a beautiful statistics output - phpMemcachedAdmin

This is a regular PHP script. You open it on your website and get a beautiful design.
There is no need to configure anything. By default it connects to localhost:11211
You can download it on the official page.

Memcache usage examples

Let's say we have the string "test111", we want to cache it for 1 day. Let's come up with some kind of key "key1" for it.

connect("localhost",11211); $memcache->set("key1", "test111", false, 86400); // cache for 1 day. $get_result = $memcache->get("key1"); // get data print_r($get_result); ?>

Let's complicate things a little

get($key)) ( $get_result = $memcache->get($key); print_r($get_result); ) else ( $result = "test222"; // $result is the result of some calculations or a sample from the database $memcache->set($key, $result, false, 86400); echo "recorded cache for 1 day" ?>

Only from the second launch of this script will we see our data.

I also forgot to add about the cache lifetime. Memcached has a lifetime limit of 1 month. So, if you set 365 days, then Memcached simply will not save them, and it will not give any error. Therefore, if your data does not change for a long time and you want to set the maximum lifetime, then specify false
$memcache->set($key, $result, false, false);

Features of key naming. It is better to use md5(key) as the key, because the maximum key length is 250 characters and spaces cannot be used. And when you cache SQL queries with a condition, the key will be like $key = "blog_id_1 WHERE activity=1 AND ... AND ... LIMIT 10"

Moreover, you also need to add some kind of constant to the key, which determines which site the cache belongs to.
$key = md5(PROJECT."key2"); // where the constant is PROJECT="site.com"

If this is not done, then a second site on the same server may overwrite the data of the first site with the same key. The fact is that Memcached does not have authorization, like a database, for example, so you have to restrict access in this way. In short, Memcached is such a big dump of key-value pairs. Therefore, all sites store their cache in one Memcached. At the same time, we cannot, for example, take the last 10 recorded elements (such as in the LIMIT 10 database). The structure of Memcached is extremely simple, but due to this we get high performance.

Tagging

Since Memcached is extremely simple (the data is not interconnected in any way - there is only a key-value relationship), some difficulties arise in practice. Let's say we have blogs like on Habré. We wrote a post and saved it in the cache. We created several key-value pairs: a cache for the post itself, a cache for the blog in which this post is displayed, a cache for the live broadcast, a cache for displaying the user’s posts in the user’s profile, etc.

$memcache->set("post_id_2211", "data");
$memcache->set("post_blog_id_11", "data");
$memcache->set("live_posts", "data");
$memcache->set("post_user_id_331", "data");

But suddenly the moderator deleted the post. We need to clear all caches that are associated with this post.

$memcache->delete("post_id_2211");
$memcache->delete("post_blog_id_11");
$memcache->delete("live_posts");
$memcache->delete("post_user_id_331");

In short, due to the simplicity of Memcached, we have to manually produce extra code. Moreover, we must constantly remember which caches are associated with other caches. The solution to the problem is very simple. We attach a tag or several tags to each cache element.
You can read more.

Practice

In practice, no one uses pure Memcached. Usually they use some kind of wrapper class that supports tagging. The most common solution is ZendCache

Download in one archive with all examples
Let's put the ZendCache class in the lib folder

The structure should be like this when viewed from the root
/lib/DklabCache/...
/class/Cache.class.php
/stat.php
/get_post.php
/update_post.php

Wrapper class (or as it is also called - wrapper) using ZendCache

array(array("host" => MEMCACHED_HOST, "port" => MEMCACHED_PORT, "persistent" => false),), "compression" => false,);

self::$instance = new Cache;

self::$instance->memcache = new Dklab_Cache_Backend_TagEmuWrapper(new Zend_Cache_Backend_Memcached($aConfigMem));

) else ( return NULL; ) ) return self::$instance;

) public function get($key) ( return $this->memcache->load($key); ) public function set($key, $value, $tags=array(), $timeLife=false) ( return $this ->memcache->save($value, $key, $tags, $timeLife); public function delete($key) ( $this->memcache->remove($key); ) public function clean($cMode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) ( return $this->memcache->clean($cMode,$tags); ) public function __construct() ( ) public function __clone() ( ) ) ?>

This is our singleton class, in simple words, on the first call an instance of the class is created (read, connection to Memcached) and used on the next call. Thus, within one script we do not create unnecessary connections and save resources.

The CACHE_USE constant is specified separately in the config. Using it you can enable/disable caching.

The "compression" => false parameter means that we do not compress the data in the cache. Compression is necessary to save memory space, but compression takes some time. Therefore, if the amount of memory is not critical for you, then we disable it more concisely.

"servers" => array(array("host" => "11.33.45.11", "port" => 11211, "persistent" => false), array("host" => "11.33.45.12", "port " => 11211, "persistent" => false), array("host" => "11.33.45.13", "port" => 11211, "persistent" => false),)

In a good way, such things need to be moved out of the class into the config.

Now we connect this class to the script in which we want to cache something
Let's say a post output script (in the archive this is get_post.php)
The examples are certainly not the best, but it’s better than nothing at all.
I specifically disabled work with the database so that you have fewer problems.

get($key_cache)))( echo "data taken from cache"; return $data; ) else ( // find the post in the database (execute select) //$data = $DB->selectRow("SELECT * FROM post WHERE id=?d", $postID); // to simplify the example, we take a ready-made array (the post is linked to a blog with ID=3) $data = array("id"=>$postID, "blog_id"=>3, "title "=>"News 111", "text"=>"some text"); if (!empty($data)) ( if (isset($Cache)) ( $Cache->set($key_cache, $ data, array("post_update", "post_update_".$postID, "post_blog_".$data["blog_id"]), 3600*24*10); echo "saved data in cache" ) return $data ) else; return null; ) ) $postID = 25; $post = get_post($postID); print_r($post); ?> We want to take a post with id=25. When you call it for the first time, you should see the message “saved data in cache.” When you call again, you will see the message “data taken from cache.” Now let's try to update the post (run the update_post.php script)query("UPDATE post SET blog_id =?d, title=?, text=? WHERE id=?d", $blogID, $title, $text, $postID);

// clear tags associated with this post $Cache = Cache::getInstance();

if (isset($Cache)) ( $Cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("post_update", "post_update_".$postID, "post_blog_".$blogID)); ) return true; ) $postID = 25; update_post($postID, 3, "test", "test test"); ?> Then we run the get_post.php script and see that there was no data in the cache and we saved it there again: “saved data to cache”. In fact, the hardest thing about caching is

putting the correct tags

  • . So that when you update a post, the data in which this post lies is updated.
  • In the example above these were tags
  • "post_update_".$postID - the post itself (usually the post output page)

"post_blog_".$blogID - blog page where a list of posts from this blog is displayed

Translated as “pack of dogs.” Let's say you have some complex sample from the database for 2 seconds. It is not in the cache yet (or we reset the cache). The first user arrives, a request is sent to the database, and only after 2 seconds this data will appear in the cache. So, in these 2 seconds, 10 more people can visit the site, who initiate 10 more of the same complex requests to the database (since there is no data in the cache yet, and the first request is still being executed). This results in a pack of dogs that load the server.

it looks something like this :)

The solution to the problem is described.
The code above does not provide protection against the dog-pile effect. In my case, there is no such high traffic and long requests.

A publication has already been made with . Let's return to this topic and look at the practice of working with memcached using examples.

Unfortunately, I still don’t get around to actively blogging, but the first person has finally appeared to respond to . His name Vladislav Klimenko and he is the author of this post, and I only act as an editor. Maybe this example will encourage other readers to participate in the return Insight IT to life.

Sincerely,
Ivan Blinkov

So, a few words about the subject of conversation. memcached is a distributed in-memory object caching system. Developed by the company (by the way, they are the authors of not only memcached, but also other interesting projects). But maybe more about them next time. Typically, memcached is used by applications to temporarily store data that needs to be read frequently. Applications do not (usually) interact directly with the memcached server, but operate using client libraries. Currently, libraries have been created for many programming languages ​​(and for some, several alternative ones) - a complete list of client libraries is available on. In general, this scheme is similar to working with a database, familiar to many developers.

We will consider installing and using memcached for Linux. Also, when considering examples in PHP and reviewing session caching, you will need PHP and Apache. They may need to be installed, but we won't focus on installation issues.

memcached server

Let's start installing memcached. On almost all Linux distributions, memcached can be installed from repositories. If you want to collect the latest version, you can look at (at the time of writing these lines, the latest version is). You may also need to install libevent. Latest stable version -

We assemble, install and run memcached in message output mode. It's interesting to see what happens to him:

The process starts and waits for connections (by default on port 11211). The server part is ready to process client connections and cache the received data.

But for an app developer, this is only half the journey. You need to support working with memcached in your application. To do this, let's look at some existing memcached client libraries.

memcached clients

Of the variety of client libraries, we will consider two:

  • libmemcached (for C);
  • PECL extension for PHP (built on the previous library).

Si

The libmemcached library is currently being actively developed and seems to be the most suitable choice when working with C and PHP. Also, the client library itself includes additional utilities for working with memcached, allowing you to view, set, and delete values ​​in the memcached cache. By the way, it is surprising that the set of utilities does not come with the server part, but with the client library.

So, let's start installing libmemcached. As of this writing, the current version of libmemcached is . We compile and install. First, let's enjoy reading the man pages:

man libmemcached man libmemcached_examples

The library comes with descriptions of simple examples of use. For more interesting methods of application, it makes sense to look into the source codes of the utilities, since everything goes together.

  • memstat - displays information about the memcached server
  • memcat - returns value by key
  • memrm - deletes a value by key
  • memdump - produces a list of keys

First, let's see what the memcached server, which we launched a little earlier in message output mode, says. Let's request server statistics using the memstat utility:

memstat --servers localhost Listing 1 Server Server: localhost (11211) pid: 14534 uptime: 1950 time: 1247390264 version: 1.4.0 pointer_size: 32 rusage_user: 0.0 rusage_system: 0.0 curr_items: 0 total_items: 0 bytes: 0 curr_connections: 10 total _connections : 11 connection_structures: 11 cmd_get: 0 cmd_set: 0 get_hits: 0 get_misses: 0 evictions: 0 bytes_read: 0 bytes_written: 0 limit_maxbytes: 67108864 threads: 5

We received statistics - therefore memcached is functioning and responding to requests.

So, at the moment, the memcached server and client library are ready to use. All that remains is to implement the use of memcached in the application being developed. As for the application, everything is in the hands of the developers, and we will look at a small example of working with basic functions.

memcached provides the following set of basic functions (there are, of course, more, but here are the main ones):

  • set- cache a key-value pair
  • add- add a value to the cache, provided that there is no value with such a key in the cache yet
  • replace- updates the cache provided that a value with such a key is already in the cache
  • get- gets a value from the cache using the specified key

Example C program

#include "stdio.h" #include "string.h" #include "memcached.h" int main ( void ) ( char * key = "key" ; char * value = "value" ; uint32_t flags = 0 ; size_t length = 0 ; char * value2 = NULL ; memcached_return rc ; !} // 1. create a structure for working with the cache memcached_st * memc = memcached_create(NULL); // 2. specify the server with which we will work memcached_server_add(memc, "localhost", 11211); // 3. store the key-value pair in the cache rc = memcached_set (memc, key, strlen (key), value, strlen (value) + 1, (time_t) 0, flags); if (rc == MEMCACHED_SUCCESS ) ( ) else ( } // handle the error// 4. get the value if (rc == MEMCACHED_SUCCESS ) ( ) else ( } value2 = memcached_get(memc, key, strlen(key), &length, &flags, &rc); if (rc == MEMCACHED_SUCCESS ) ( printf ( "%s \n " , value2 ); free ( value2 ); ) else (

// 5. release the structure

memcached_free(memc);

return 0 ;

)

The program consists of 5 main operations and does not need any special comments. It can only be noted that in point 2 you can add many servers if you use a distributed system. To compile, you may have to explicitly specify the paths to the libraries:!

For more details, look at the messages on the memcached server:

<32 new auto-negotiating client connection 32: Client using the ascii protocol 32 STORED 32 sending key key >32 END<32 quit <32 connection closed.

This example shows the following events: client connection, setting a key-value pair, reading key data, and client disconnection.

Let's look at the statistics on the server:

memstat --servers localhost Listing 1 Server Server: localhost (11211) pid: 14534 uptime: 4659 time: 1247392973 version: 1.4.0 pointer_size: 32 rusage_user: 0.0 rusage_system: 0.0 curr_items: 1 total_items: 1 bytes: 58 curr_connections: total_connections : 13 connection_structures: 11 cmd_get: 1 cmd_set: 1 get_hits: 1 get_misses: 0 evictions: 0 bytes_read: 58 bytes_written: 58 limit_maxbytes: 67108864 threads: 5

The next two lines show that a value has appeared in the cache:

curr_items: 1 total_items: 1

Let's look at this value:

memcat --servers localhost key value

So, the application using memcached is ready.

PHP

First, let's install the PECL extension for PHP - memcached

pecl install memcached

At this stage, you may receive an error message like:

ERROR: "phpize" failed

This means that the php-dev package or its equivalent is not installed. Install it and you can try again:

pecl install memcached install ok: channel://pecl.php.net/memcached-1.0.0 You should add "extension=memcached.so" to php.ini

As we were advised, add extension=memcached.so to php.ini and restart Apache.

Let's look at the information about the PHP used:

memcached support enabled Version 1.0.0 libmemcached version 0.31 Session support yes igbinary support no

Example program in PHP

You can safely use calls to memcached from PHP. As usual, let's look at an example:

addServer("localhost", 11211);

$m -> set ("phpkey" , "phpvalue" );

var_dump ( $m -> get ( "phpkey" ));

?>

The result of this script:

string(8) "phpvalue"

So, your PHP application using memcached is ready.

Caching session data Memcached can also be used as a session data store for PHP. This approach is often used in real applications. Let's look at what needs to be done for this. Making changes to php.ini

;session.save_handler = files session.save_handler = memcached

Restart Apache - and you're done!

Now we need to check that now the session data is actually stored not on disk, but in memcached.

Let's look at the work of a simple script that adds something to a session:

We run the script, it enters data into the session, after which we look at the cache

memdump --servers localhost key keyphp memc.sess.key.3ff8ccab14424082ff83a6dfbcf0941f

So, to the keys we are familiar with from the previous examples, a key with the characteristic name memc.sess.key has been added..

Session data storage has been moved to the caching system. You can read more detailed information on working with memcached from PHP.

Conclusion

We looked at installation and examples of using memcached. It should be especially emphasized that memcached is not a data storage system, so in practice memcached is almost always used in conjunction with a database. You should also pay attention to timely invalidation of data in the cache and security issues. In general, the topic is interesting, and is still far from closed.

Today I will present you with a small piece of code that will teach you how to interact with Memcache. In order to install Mediatemple on your hosting, you need SSH data.

Who uses Memcache?

Memcache was developed by Danga Interactive in order to increase the speed of the LiveJournal.com portal. Memcache reduces the loading time from the database to almost zero, which increases page loading speed for users, accelerated resource management, etc. At the moment, FaceBook is the largest user of the Memcache service. Considering the number of people arriving on FaceBook every day, he almost overwhelmed this service - and a separate place was allocated for them.

What is Memcache?

Well, is it interesting? Memcache is a universal system for distributing cached items. If there is nothing in the cache, then a request is made to the database and the results are written to Memcache:

Memcache provides 5 functions:

  • get() - retrieves a value by key
  • set() - sets the value
  • add() - adds cache if it doesn't exist
  • replace() - replaces the cache
  • flush() - deletes all cached data

Code

If you have installed Memcache, then you can start using it. There is an opinion that a lot of cache is bad. I absolutely disagree with this! The faster your site loads, the better!

  • The first two lines connect to Memcache.
  • Next comes the database connection script.
  • Then we create a key. When we want to put data into Memcache, we need to pass 3 elements for insertion: key, value and cache lifetime. The key is required to gain access to the data. In this example, you can see that I am using the query hash as the MD5 key.
  • Next we check if the cache exists. The check will return true or false. If it exists, we get access to it.
  • If there is no cache, then we connect to the database and get the values. To create a cache, we use the following expression: $memcache->set($key, $row, TRUE, 20); $row stores an array of what we got from the database. 20 is the cache lifetime in seconds.

$memcache = new Memcache; $memcache->connect("127.0.0.1", 11211) or die ("Could not connect"); include("includes/connect.php"); //create a key, then test the cache $key = md5("SELECT * FROM memcached_test where name="ashley""); $get_result = $memcache>get($key); if ($get_result) ( echo $get_result["name"]; echo $get_result["username"]; echo "Data Pulled From Cache"; ) else ( // Get data from the database and create a cache $query="SELECT * FROM memcached_test where name="ashley";"; $result = mysql_query($query); $row = mysql_fetch_array($result); print_r($row); $memcache>set($key, $row, TRUE, 20) ; // Store the result for 20 seconds echo "Data Pulled from the Database" ;

This is a very basic example of using memcache, but I hope it was a good start for you.