How i can design a cache system using PDO and memcached?
I'm using PDO for connect to the database in a system where I want implement memcached.
I don't know what keys use for开发者_运维技巧 caching the results because I can't get the string of the final query with PDO (because the prepared statements).
Any good idea for resolve this?
Thanks in advance.
If you're just going to cache query results directly based on query string, Mysql's query cache already does this for you. Don't reinvent the wheel. The one potential difference is Mysql's query cache is aggressively invalidated so that stale (out of date, incorrect) data is never returned; depending on how you handle invalidation, your strategy may further reduce database load, but at the cost of serving stale, out of date data on a regular basis.
Additionally, you won't really be able to selectively expire your various cache keys when updates happen (how would you know which query strings should be expired when an insert/update runs?); as a result you'll just have to set a short expiration time (probably in seconds), to minimize the amount of time you're serving stale data. This will probably mean a low cache hit rate. In the end, the caching strategy you describe is simple to implement, but it's not very effective.
Make sure to read the "Generic Design Approaches" section of the memecached FAQ. A good caching strategy deletes/replaces cached data immediately when updates occur -- this allows you to cache data for hours/days/weeks, and simultaneously never serve out of date data to users.
Here is interesting tutorial it might be helpful - http://techportal.inviqa.com/2009/02/16/getting-started-with-memcached/
I guess you can automate the process by implementing a function like this:
function query($name, $sql, $params, $db, $cache) {
$result = $this->cache->get($name);
if (!$result) {
$stmt = $db->prepare($sql);
$exec = $stmt->execute($params);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$cache->add($name, $result);
}
return $result;
}
精彩评论