I have posted before on how to use Memcached to reduce database load, but I failed to give a sound example. Hopefully this will rectify that. Please read this post to catch up if you haven’t already. otherwise I will assume you have experience with Memcached.
In this scenario, you have a custom built blog application that has a section with the latest posts. Instead of constantly pulling this text from the database or saving the output to text files, which can be slow, saving the test into memory may be the best solution.
Take the following code:
$sql = "SELECT * FROM posts ORDER BY date LIMIT 5";
$query = mysql_query($sql);
if(mysql_num_rows($query)
{
while($row=mysql_fetch_array($query))
{
echo "
".$row['title']."
";
}
}
Lets make that faster.
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
if(!$memcache->get('recent_posts'))
{
$sql = "SELECT * FROM posts ORDER BY date LIMIT 5";
$query = mysql_query($sql);
$post_array = array();
if(mysql_num_rows($query)
{
while($row=mysql_fetch_array($query))
{
$post_array[] = $row;
}
}
//recent expires in one hour
$memcache->set('recent_posts',$post_Array, 0, 3600);
}
$recent_posts = $memcache->get('recent_posts');
for($i=0;$i".$recent_posts[$i]['title']."
";
}
You won’t notice a large increase if your site is small, but if you have a busy site and you have a bunch of spare ram, you might as well put it to use. In the future I will show you some more examples of real-world usage of Memcached.