Memcached
By Tristup Ghosh
PHP Developer, Itobuz Tech.
What is Memcached
Memcached is a general-purpose distributed memory caching system. It is basically used to speed up dynamic
database-driven websites by caching data and objects in RAM to reduce the number of times an external data
source (such as a database or API) must be read.
Memcached is free and open-source software*, subject to the terms of the Revised BSD license. Memcached
runs on UNIX and on Windows platform. We can implement it using PHP, JAVA, DOT Net, XCODE etc.
Memcached's APIs provide a giant hash table** distributed across multiple machines. When the table is full,
subsequent inserts cause older data to be purged in least recently used (LRU) order.Applications using
Memcached typically layer requests and additions into RAM before falling back on a slower backing store, such
as a database or any file systems.
Now Memcached has been widely used in web. Most of the popular websites are using it as part of their platform
as a service technology stack.
Google App Engine, Microsoft Azure and Amazon Web Services also offer a Memcached service through an API.
* Memcached GIT : http://github.com/memcached/memcached
** FOR HASH TABLE : http://en.wikipedia.org/wiki/Hash_table
Point to be Discussed
1. Difference between web requests with and without Memcached.
2. Generic code to fetch a record in both type of request.
3. Implementing Memcached using PHP
4. Steps to install Memcached in WAMP
WEB REQUEST WITHOUT MEMCACHED
WEB REQUEST WITH MEMCACHED
Back to Index
Database
Memcached
Not found in
MemcachedApplication
Application
Application
Application
Webserver
Database
Application
Application
Application
Application
Webserver
function get_emp(int empid)
{
data = db_select("SELECT * FROM employeeWHERE empid = ?", empid);
return data;
}
function get_emp (int empid)
{
/* first search in the cache */
data = memcached_fetch(" emprec:" + empid);
if (!data)
{
/* if not found : request goes to database */
data = db_select("SELECT * FROM employee WHERE empid =?", empid);
/* then store in cache until next get */
memcached_add(" emprec:" + empid, data); /* serialized data */
}
return data;
}
FETCH THE RECORD FROM DATABASE
FETCH THE RECORD FROM MEMCACHED
Cont…
function update_emp(int empid, string dbUpdateString)
{
/* update database first*/
result = db_execute(dbUpdateString);
if (result)
{
/* database update successful : fetch data to be stored in cache */
data = db_select("SELECT * FROM employee WHERE empid = ?", empid);
/* then store it in cache */
memcached_set(“emprec:" + empid, data);
}
}
Back to Index
In this way you can fetch the user data from the Memcached. If any database update
action occurs regarding the user data, Memcached should be updated respective to that
userid. Therefore, in addition to creating an "add" call, an update call would also be
needed using the Memcached set function.
Add : Set the value in memcache if the value does not exist; returns FALSE if value exists
Set : Store the value in the memcache memory (overwrite if key exists)
<form method="post">
<b>Film</b>: <input type="text" size="20" name="film"><input type="submit">
</form>
<?php
$memc = new Memcache;
$memc->addServer('localhost','11211');
if(!empty($_POST['film']))
{
echo "Loading data...n";
$mfilms = $memc->get($film);
if ($mfilms)
{
echo "<p>Film data for %s loaded from memcache</p>", $mfilms['title'];
foreach (array_keys($mfilms) as $key)
{
echo $key.":".$mfilms[$key];
}
} else
{
$mysql = mysql_pconnect('localhost','dbname','pass','filmdb') or die(mysql_connect_error());
$sql = "SELECT * FROM film WHERE title='".$film."'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$memc->set($row['title'], $row);
echo "<p>Loaded (%s) from MySQL</p>".$row['title'];
}
}
?>
Back to Index
Important Methods to remember
 addserver()
To create a simple connection to memcached instances. We can add more than one
memcached instance to an object.
 get()
Returns the value stored in the memory by it's key
 set()
Store the value in the memcache memory (overwrite if key exists)
 add()
Set the value in memcache if the value does not exist; returns FALSE if value exists.
 replace()
Replace an existing value
 delete()
Delete a record or set a timeout
 increment()
Increment an existing integer value
 decrement()
Decrement an existing value
 Flush()
To clear the cache.
Steps to install Memcached in WAMP
1. First download memcached.exe and copy it into a folder [ C:memcached ].
2. Download MSVCP71.DLL, msvcr71.dll and copy it to C:windowssysWOW64
3. Run from Command Prompt C:memcachedmemcached.exe -d install
4. Run from Command Prompt C:memcachedmemcached.exe -d start
5. Download php_memcache.dll and copy to C:wampbinphpphp5.3.4ext
6. Restart Apache and Enable the service for memcache.
Back to Index
Thanks
Application

1

  • 1.
    Memcached By Tristup Ghosh PHPDeveloper, Itobuz Tech.
  • 2.
    What is Memcached Memcachedis a general-purpose distributed memory caching system. It is basically used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read. Memcached is free and open-source software*, subject to the terms of the Revised BSD license. Memcached runs on UNIX and on Windows platform. We can implement it using PHP, JAVA, DOT Net, XCODE etc. Memcached's APIs provide a giant hash table** distributed across multiple machines. When the table is full, subsequent inserts cause older data to be purged in least recently used (LRU) order.Applications using Memcached typically layer requests and additions into RAM before falling back on a slower backing store, such as a database or any file systems. Now Memcached has been widely used in web. Most of the popular websites are using it as part of their platform as a service technology stack. Google App Engine, Microsoft Azure and Amazon Web Services also offer a Memcached service through an API. * Memcached GIT : http://github.com/memcached/memcached ** FOR HASH TABLE : http://en.wikipedia.org/wiki/Hash_table
  • 3.
    Point to beDiscussed 1. Difference between web requests with and without Memcached. 2. Generic code to fetch a record in both type of request. 3. Implementing Memcached using PHP 4. Steps to install Memcached in WAMP
  • 4.
    WEB REQUEST WITHOUTMEMCACHED WEB REQUEST WITH MEMCACHED Back to Index Database Memcached Not found in MemcachedApplication Application Application Application Webserver Database Application Application Application Application Webserver
  • 5.
    function get_emp(int empid) { data= db_select("SELECT * FROM employeeWHERE empid = ?", empid); return data; } function get_emp (int empid) { /* first search in the cache */ data = memcached_fetch(" emprec:" + empid); if (!data) { /* if not found : request goes to database */ data = db_select("SELECT * FROM employee WHERE empid =?", empid); /* then store in cache until next get */ memcached_add(" emprec:" + empid, data); /* serialized data */ } return data; } FETCH THE RECORD FROM DATABASE FETCH THE RECORD FROM MEMCACHED Cont…
  • 6.
    function update_emp(int empid,string dbUpdateString) { /* update database first*/ result = db_execute(dbUpdateString); if (result) { /* database update successful : fetch data to be stored in cache */ data = db_select("SELECT * FROM employee WHERE empid = ?", empid); /* then store it in cache */ memcached_set(“emprec:" + empid, data); } } Back to Index In this way you can fetch the user data from the Memcached. If any database update action occurs regarding the user data, Memcached should be updated respective to that userid. Therefore, in addition to creating an "add" call, an update call would also be needed using the Memcached set function. Add : Set the value in memcache if the value does not exist; returns FALSE if value exists Set : Store the value in the memcache memory (overwrite if key exists)
  • 7.
    <form method="post"> <b>Film</b>: <inputtype="text" size="20" name="film"><input type="submit"> </form> <?php $memc = new Memcache; $memc->addServer('localhost','11211'); if(!empty($_POST['film'])) { echo "Loading data...n"; $mfilms = $memc->get($film); if ($mfilms) { echo "<p>Film data for %s loaded from memcache</p>", $mfilms['title']; foreach (array_keys($mfilms) as $key) { echo $key.":".$mfilms[$key]; } } else { $mysql = mysql_pconnect('localhost','dbname','pass','filmdb') or die(mysql_connect_error()); $sql = "SELECT * FROM film WHERE title='".$film."'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); $memc->set($row['title'], $row); echo "<p>Loaded (%s) from MySQL</p>".$row['title']; } } ?> Back to Index
  • 8.
    Important Methods toremember  addserver() To create a simple connection to memcached instances. We can add more than one memcached instance to an object.  get() Returns the value stored in the memory by it's key  set() Store the value in the memcache memory (overwrite if key exists)  add() Set the value in memcache if the value does not exist; returns FALSE if value exists.  replace() Replace an existing value  delete() Delete a record or set a timeout  increment() Increment an existing integer value  decrement() Decrement an existing value  Flush() To clear the cache.
  • 9.
    Steps to installMemcached in WAMP 1. First download memcached.exe and copy it into a folder [ C:memcached ]. 2. Download MSVCP71.DLL, msvcr71.dll and copy it to C:windowssysWOW64 3. Run from Command Prompt C:memcachedmemcached.exe -d install 4. Run from Command Prompt C:memcachedmemcached.exe -d start 5. Download php_memcache.dll and copy to C:wampbinphpphp5.3.4ext 6. Restart Apache and Enable the service for memcache. Back to Index
  • 10.