How do I add memcache to my database class?
I'm just trying to figure out how I can add memcache to a database class. I haven't tested the code below (it's even the first time I'm trying to add memcache to my code), but does it at least make sense? Or can someone think of a better way to do it?
Database Class (simplified)
database
{
protected $result;
protected $row;
protected $cache_result;
public function query($sql, $cache = false)
{
/* only use memcache for selected queries */
if($cache)
{
$key = md5('query'.$sql);
$this->result = $memcache->get($key);
if($this->result == null)
{
$this->result = mysql_query($sql);
$this->cache_result = mysql_fetch_object($sql);
/* cache for 1 hour */
$memcache->set($key, $this->cache_result, 0, 3600);
}
}
else
{
$this->result = mysql_query($sql);
}
return $this->result;
}
public function fetch($sql)
{
$this->row = mysql_fetch_assoc($sql);
return $this->row;
}
}
PHP (simplified)
include_once $_SERVER['DOCUMENT_ROOT'].'/loader.php';
$sql = "SELECT * FROM `table` WHERE `this` = 'that'";
/* use memcache for the query below */
$开发者_如何学Goa = $database->query($sql, true);
$b = $database->fetch($a);
PHP (loader)
$database = new database();
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211);
I won't vouch for the syntax as I don't code PHP, however it looks like the right approach with the following observations.
You shouldn't really take the md5 of 'query'.$sql. It would be better to do 'query'.md5($sql) so that the prefix acts like a pseudo namespace in that you can guarantee that 'ns1:'.md5($sql) won't clash with 'ns2:'.md5($sql). There are cleverer ways of using such pseudo namespaces that the following FAQ handles well.
http://code.google.com/p/memcached/wiki/FAQ#How_do_I_access_memcached?
The next thing I would say is I would be wary of having an explicit expiration time. It's often better to let the cache handle which items to dump when it needs the space. If you have a busy site, you can find that explicit expirations will cause unnecessary cache dumps and performance issues that you are meant to be solving by adding the cache. There is a good starting point on some of the issues here;
http://highscalability.com/strategy-break-memcache-dog-pile
And given the title, I can't resist linking to this article as well;
http://blog.craigambrose.com/past/2007/11/13/caching_makes_your_brain_explode/
I therefore tend to explicitly invalidate the appropriate cache keys when data changes, rather than using arbitrary time constraints. But either way, try to understand the consequences of whichever approach you are taking.
BUT
The first thing I would actually say is ... have you tuned your database yet? In particular, are you using the query cache that can be enabled and configured? This is likely to have a far more dramatic impact on performance than adding memcached - until you are scaling well beyond the capacity of a single server of course.
精彩评论