我有一个项目,这是一个结果数据库的几个体育赛事系列。正如你可以想象的那样,内容大体上保持不变。我想缓存一些内容以保存数据库查询。
该项目是使用PHP构建的,并且使用了自定义的MVC。您将在何处添加缓存逻辑?
发布于 2012-11-22 00:41:19
使用Memcached。如下所示,缓存查询的结果,并尝试在DB之前从缓存中检索。
编辑:已添加json_encoding数据...json_encode比PHP的默认数组序列化稍微快一些,并且可以被访问数据的其他应用程序使用
Memcached默认使用FastLZ压缩。
// The ID of the item you're looking for (from $_GET or whatever)
$id = 1;
// Create a memcached instance
$m = new Memcached();
$m->addServer('localhost', 11211);
// Try retrieving the event from memcached
$data = $m->get('event_' . $id);
if ($data) {
// If you found data in memcached, decode it for use in code
$data = json_decode($data);
} else {
// If you didn't find the data in memcached, try retrieving from the DB
$result = mysqli_query('SELECT * FROM events WHERE id = ' . $id);
// If you found results in the DB...
if ($data = mysqli_fetch_assoc($result)) {
// Save them to memcached for future calls
// Note: here, I'm using the optional param to expire it after 1 day
$m->set('event_' . $id, json_encode($data), 86400);
}
}
// Now you can use your data
var_dump($data);编辑后可在代码中添加注释
发布于 2012-11-22 00:38:19
我会使用memcached,因为使用它的http://memcached.org/构建缓存解决方案非常容易
我通常将缓存逻辑放在控制器中,尽管模型通常可能更适合它,原因是模型使用的上下文可能会影响缓存策略
将其放入模型中使得缓存策略与其余的数据访问功能处于同一位置,这是正确的,这意味着您可以交换模型,缓存代码也会随之移动。当你有复杂的失效而不能放入模型中时,就会出现这种情况。
“计算机科学中只有两件很难的事情:缓存失效和命名”Phil Karlton
发布于 2012-11-22 00:41:30
可以使用Memcache(d)缓存对象,这对于多服务器设置非常有用。对于单个服务器,您可以将内容存储在APC/Xcache等提供缓存功能的服务器中。
我会在dataaccess方法中缓存数据。
https://stackoverflow.com/questions/13497825
复制相似问题