PHP Opcache is a good caching plugin for PHP but what if you wanted a quicker in code way of selectively caching MySQL results in memory. More information on the underlying memcached.
Official Description:
Description: A high-performance memory object caching system. Danga Interactive developed memcached to enhance the speed of LiveJournal.com, a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a memcache miss.
Danga Interactive developed memcached to enhance the speed of LiveJournal.com, a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a memcache miss.
Memcached optimizes specific high-load serving applications that are designed to take advantage of its versatile no-locking memory access system. Clients are available in several different programming languages, to suit the needs of the specific application. Traditionally this has been used in mod_perl apps to avoid storing large chunks of data in Apache memory, and to share this burden across several machines. Caching other content is a good idea too.
Homepage: http://www.danga.com/memcached/
Follow this guide to install memcached.
Here is a simple script to query and cache MySQL data for 10 seconds.
$start = microtime(true); $mem = new Memcached(); $mem->addServer("127.0.0.1", 11211); mysql_connect("localhost", "dbuser", "dbpass") or die(mysql_error()); mysql_select_db("databasename") or die(mysql_error()); $query = "SELECT COUNT(*) AS TotalUsers FROM databasename WHERE 1"; $querykey = "TotalUsers" . md5($query); $result = $mem->get($querykey); if ($result) { print " Data was: " . $result[0] . " "; print " Caching success! Retrieved data from memcached! "; } else { $result = mysql_fetch_array(mysql_query($query)) or die(mysql_error()); $mem->set($querykey, $result, 10); print " Data was: " . $result[0] . " "; print " Data not found in memcached. Data retrieved from MySQL and stored in memcached for next time. "; } $end = microtime(true); $time = number_format(($end - $start), 6); echo 'This page loaded in ', $time, ' seconds';
For me, the cached page loaded 0.022076 seconds faster than without Memcache per page. A small MySQL database is fast but a cached database is faster.
V1.2 added memcached link
Donate and make this blog better
Ask a question or recommend an article
[contact-form-7 id=”30″ title=”Ask a Question”]