ImprovingWebAppPerformanceWith? Memcached

Source: Internet
Author: User
Response. Thisisgreatforlongtermstorageanddataanalysis, buttheresabetteroptionformanyshort-termneeds: memcached. Itsagre

When we think of storage in a web application our first thought is usually a traditional database like MySQL. this is great for long term storage and data analysis, but theres a better option for short-term needs: memcached. its a gre

When we think of storage in a web application our first thought is usually a traditional database like MySQL. this is great for long term storage and data analysis, but there's a better option for short-term needs: memcached. it's a great choice for saving bits of information between page requests and increasing performance. in this introduction we'll show you how to start using memcached with PHP.

Introduction

Memcached is simply a server with an interface to let you store things in memory. this can run on the same machine as your web server, but scalability comes from distributing instances into SS multiple servers. all you need is the memcached daemon running and PHP provides a simple interface with a PECL library. on a Debian-based Linux system this is as easy:

$ sudo apt-get install memcached$ sudo service memcached start$ sudo pecl install memcached$ sudo service httpd restart

Now we shoshould mention there are technically two PHP libraries available to work with memcached. the older library is called "memcache" and is lacking in some features. the newer "memcached" library uses libmemcached and is generally preferred.

The first step in PHP is to connect to the server. connections can be persisted into SS requests, which is nice for performance. then add to the server list as needed. in this case we'll use a locally running instance on the default port:

function get_memcached() {    // Set a persistent connection ID    $mc = new Memcached('webapp');    // Set a short timeout (in milliseconds) so if the server goes down    // it doesn't take down our site with it    $mc->setOption(Memcached::OPT_CONNECT_TIMEOUT, 1000);    if ( !$mc->getServerList() ) {        if ( !$mc->addServer('localhost', 11211) ) {            error_log('Could not add memcached server.');            return false;        }    }    return $mc;}

Now you can read and write PHP variables to memcached with simple functions based on keys you define. they'll be serialized and deserialized automatically. you can't write resources like database connections or result sets, but you can turn those result sets into arrays and store those.

$mc->set('list', array(1, 2, 3));$list = $mc->get('list');
Storing Data

Let's say we want to store a list of recently visited URLs for each logged in user. we cocould use sessions but that wouldn't work with SS devices and it'll disappear as soon as the session is cleared. we cocould use a database but that's slow for this kind of data that's most likely not critical to our system. using memcached this is easy:

$user_id = 123;  // The current user's ID$recents = array();if ($mc = get_memcached()) {    // Get any stored in memcached    $recents = $mc->get("recents-$user_id");    if (!$recents) {        $recents = array();    }    $recents[] = $_SERVER['REQUEST_URI'];    $recents = array_unique($recents);    $recents->set("recents-$user_id", $recents);}print_r($recents);
Caching

Now let's really boost your web application by caching database results. database queries are usually the biggest bottleneck in server processing, so avoiding duplicate queries by caching results in memory can provide a huge performance gain. the simplest method is to query and store just with primary keys. typically it's best that the cached value be deleted when the database record is updated so a user never sees any out-of-date values.

function store_product($id, $name, $price) {    // Create or update the product in the database    $db = get_db();    $qry = $db->prepare('REPLACE INTO product (id, name, price) VALUES (:id, :name, :price)');    $qry->bindParam(':id', $id);    $qry->bindParam(':name', $name);    $qry->bindParam(':price', $price);    $qry->execute();    // Remove outdated values from cache if it's there    if ($mc = get_memcached()) {        $mc->delete("product-$id");    }}function get_product($id) {    $product = null;    // First check the cache    if ($mc = get_memcached()) {        $product = $mc->get("product-$id");    }    if (!$product) {        // Not in the cache; check the db        $qry = $db->prepare('SELECT * FROM product WHERE id = $id');        $qry->bindParam(':id', $id);        if ($qry->execute()) {            $product = $qry->fetch();            // Cache for future use            if ($mc) {                $mc->set("product-$id", $product);            }        }    }    return $product;}
Caveats

As with any technology choice there are limitations and things to watch out:

  • The max length of a key is 250 bytes. Keep your keys simple and short.
  • The default max value size is about 1 MB. This isn't the right place to store large values.
  • Storage isn't locked for reading or writing in the way database records can be locked. Just be aware that any web request can update any value at any time.
  • Be sure your memcached servers have enough combined RAM.
Next Steps

There's more you can do with memcached:

  • Cached values can have timeouts. This is useful when data shocould be cached for a set period of time instead of deleted manually.
  • SimpleincrementAnddecrementMethods are useful for keeping quick counters between requests.
  • With memcached configured correctly you can share data between applications written in your programming ages.

Give memcached a try. In the right scenarios it's a very simple and valid tive solution to maximize your web app performance.

Read the full article at: Improving Web App Performance With Memcached

Related Posts

  1. PHP Woot Checker-Tech, Wine, and Shirt Woot
  2. Book Review: Enterprise AJAX-Strategies For Building High Performance Web Applications
  3. Override WordPress URL
  4. PHP, Microsoft SQL Server (MSSQL), and IIS: Connect and Query with ODBC
  5. Upgrade Node. js via NPM

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.