Memcached is an open source, high performance memory caching system that can be used as a temporary database. It can be used for storing temporary data instead of over loading the actual database.

Memcached stores the data in key-value format. The data stored can be string as well as objects.

Memcached is used over TCP / UDP. Hence, we need to start memcached separately on a system to work.

Installing Memcached on Ubuntu

  1. First of all, we will update Ubuntu Repository
     sudo apt-get update
  2. Next, we execute the command to install memcached and php-memcached library:
     sudo apt-get install memcached
     sudo apt-get install php5-memcached
  3. Let us check if Memcached is running, the default port is 11211
    ps aux | grep memcached

    ps is used to list running processes.
    a => process from all users
    u => display process owner user
    x => show processes not attached to terminal
    grep => used for pattern matching

    To run Memcached on a different port number, example 123, run the command:

    memcached -p 123

    To start and stop Memcached, use:

    service memcached start
    service memcached stop

Using Memcached with PHP

I assume that Apache and MySQL are installed on your Ubuntu.

We will create an example with following case:

  1. User will request a record from database
  2. First time, the record will be fetched from database, stored in Memcached and returned to user
  3. After this, if same record is requested, it will be returned from Memcached instead of database

Let us initialize some data.

  1. Create a database named mem_db
  2. Create the following table:
    create table books
    (
        id int PRIMARY KEY AUTO_INCREMENT,
        title varchar(255), 
        author varchar(255)
    );
  3. Add some data to this table:
    insert into books(title, author) values('Programming in C', 'Ashutosh Pandey');
    insert into books(title, author) values('Learning AWS', 'Amit Shah');
    insert into books(title, author) values('Beginning Linux Programming', 'Neil Matthew');
  4. Create a new directory named memex in /var/www/html folder. Execute following commands for permission:
    chown -R www-data:www-data memex
    chmod -R 775 memex
  5. Create a new file named index.php in the /var/www/html/memex folder. Now add following code to the file:
    <?php
    $con = mysqli_connect('localhost', 'your_username', 'your_password') or die("Cannot connect to MySQL");
    mysqli_select_db($con, 'mem_db') or die("Cannot connect to database");
    
    $memcache = new Memcached;
    $memcache->addServer('localhost', 11211) or die ("Could not connect");
    
    $key = $_REQUEST['key'];
    $result = array();
    $result = $memcache->get($key); // try to read data from Memcached
    
    $books = array();
    if($result)
    {
       // data exists in Memcached
       $books = $result;
       $source = "memory";
    }
    else
    {
       // first time request
       $rows = mysqli_query($con, "select * from books where title like '%" . $key . "%' order by id");
       while( $row = mysqli_fetch_array($rows) )
          $books[] = $row; // result stored in array
    
       $memcache->set($key, $books, 3600); 
       // store data for 3600 seconds => 1 hour
    
       $source = "database";
    }
    
    echo json_encode(array('books' => $books, 'source' => $source));
    ?>
  6. OK, so everything is ready. Now we will check our code. Execute following commands:
     service apache2 restart
     service memcached restart

    Open a browser and execute following URL two times and observe the result:

    http://localhost/memex/index.php?key=programming

In memory data stores are a very good source to improve website performance in load conditions.