MySQL
  Home arrow MySQL arrow Page 4 - Take Some Load off MySQL with MemCached
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Take Some Load off MySQL with MemCached
By: Chris Moyer
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 3
    2008-07-29


    Table of Contents:
  • Take Some Load off MySQL with MemCached
  • A Solution - Caching
  • Enter MemCached
  • PHP MemCache PECL Extension

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Take Some Load off MySQL with MemCached - PHP MemCache PECL Extension
    ( Page 4 of 4 )

    Obviously, you are not going to want to interact with MemCached on a regular basis by using telnet and by typing out the protocol commands. Instead, client libraries are provided for nearly every popular web development language: PHP, Perl, Ruby, Python, Java, and more. Here, we’ll focus on the PHP client.

    The MemCache extension is a PECL module and may need to be installed separately from your PHP installation. In most cases, the PECL module can be installed and MemCache can be enabled without rebuilding or installing a new version of PHP. You can verify that the installation was successful by viewing the output of phpinfo(). You’ll get a section of the output with the MemCache status, number of active connections, and PECL extension version:

    memcache support

    enabled

    Active persistent connections

    0

    Revision

    $Revision: 1.80 $

    Once you’ve verified the installation, you can start using your cache! Here’s an obligatory “Hello, World!” using MemCache.

    $memcache = new Memcache;

    $memcache->connect(‘localhost’, 11211) or die(‘Memcache Connection Failed’);


    $memcache->set(‘mykey’, ‘Hello, World!’);


    $myvar = $memcache->get(‘mykey’);


    print $myvar; // Outputs: Hello, World!

    Using our news headlines example from before, here’s a better example:

    // Obtain an array of news headlines

    // Each healine is an array or headline, link and img

    function fetchHeadlines($category_id) {

    // Load cached headlines

    $memcache = getMemcache(); // wraps creation and connection of

    // MemCache object

    $articles = $memcache->get(‘articles:’ . $category_id);

    if ($articles) {

    // cache hasn’t expired

    return $articles;

    }



    // The cache doesn’t exist (probably expired)

    // Load articles from the database

    $dbh = getMysql(); // Wraps MySQL server connection

    $result = mysql_query(‘SELECT * FROM news WHERE category_id=”’ . mysql_escape_string($category_id) . ‘” AND status=1 ORDER BY publish_date DESC LIMIT 5’, $dbh);


    // Build an array of articles

    $articles = array();

    while ($article = mysql_fetch_assoc($result)) {

    $articles[] = $article;

    }


    // Store back into the cache

    $memcache->set(‘articles:’ . $category_id,

    $articles,

    0,

    60 * 15); // Store for 15 minutes


    return $articles;

    }

    In this example, we see a couple different things. The value of data used with the PHP library can be nearly any PHP variable. The data is converted into a string with the serialize() function, so numbers, strings, arrays, and most objects will be stored easily… only resources (file descriptors, database connections, MemCache connections) can not be stored effectively. Additionally, we see using the key as an example of an arbitrary lookup table: an ad-hoc string with the keyword ‘articles:’ and the category id from a simple, but effective key.

    At this point, if you’re site is loaded one time per second, you’ve decreased the number of queries for the news table from 900 every fifteen minutes to one every fifteen minutes. That's not bad for a handful of code. And even if your site traffic increases from one hit per second to 100, you’ll still only be querying the news table once every fifteen minutes.

    It is important to keep in mind that if the MemCached server crashes or the process dies, all your cache data will be lost. Always store the actual data in a database server or another persistent storage system.

    Conclusion

    While the example we created is fairly trivial, it’s easy to see how this technique can be expanded throughout your site. Other queries and other data can be cached with similar benefits. Obviously, MemCached isn’t the only solution to web scaling and data caching, but it can be a pretty useful. Often, as seen in our example, a MemCached solution can be implemented and put in place with minimal code changes, minimal time, and, hopefully, minimum downtime for your users!



     
     
    >>> More MySQL Articles          >>> More By Chris Moyer
     

       

    MYSQL ARTICLES

    - MySQL Security Tips
    - Designing a MySQL Database: Tips and Techniq...
    - The Three Most Important MySQL Queries
    - Null and Empty Strings
    - MySQL Server Tuning Tips and Tricks
    - MySQL Query Optimizations and Schema Design
    - MySQL Benchmarking Tools and Utilities
    - MySQL Benchmarking Concepts and Strategies
    - Take Some Load off MySQL with MemCached
    - MySQL Table Prefix Changer Tool in PHP
    - Using the SIGNAL Statement for Error Handling
    - Error Handling Examples
    - Error Handling
    - Completing a Search Engine with MySQL and PH...
    - Paginating Result Sets for a Search Engine B...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT