1

我有一些从数据库中获取数据的 mysql 查询,结果在 24 小时内不会改变,我想存储在缓存中,如何将结果缓存 24 小时并在过期后重新缓存它们?

<?php
$getTopics=$db->loadAssoc($db->setQuery("SELECT * ,  categories.title AS category_title, 
                                        status_topics.title as status_topic
                                        FROM contents
                                        JOIN categories ON categories.id = contents.category
                                        JOIN status_topics ON status_topics.id = contents.status "));

$getCategories           = $db->loadAssoc($db->setQuery("SELECT * FROM categories"));
$getTags                 = $db->loadAssoc($db->setQuery("SELECT * FROM status_topics"));
$getPages                = $db->loadAssoc($db->setQuery("SELECT * FROM pages"));
$getSiteInformation      = $db->loadRow($db->setQuery("SELECT * FROM settings JOIN categories"));
$getSubDomainInformation = $db->loadAssoc($db->setQuery("SELECT * FROM sub_domains"));
$getUserInformation      = $db->loadAssoc($db->setQuery("SELECT * FROM users"));
?>
4

2 回答 2

5

一个非常简单、无数据库的缓存机制:

$filename = 'cache.txt';
if (filemtime($filename) < time()-24*3600) { //older than a day
  /*get your data*/
  file_put_contents($filename, serialize(array($getCategories, $getTags, [...])); //your data in a serialized form
} else {
  $data = unserialize(file_get_contents($filename));
  list($getCategories, $getTags, [...]) = $data;
}

(显然,您应该将 [...] 替换为保存数据的变量)

于 2013-05-29T06:07:23.897 回答
1

默认情况下,mysql cahche 查询并在检索到 samre 结果时执行得更快,您还可以告诉 mysql 将结果缓存在内存中。

例如

$getCategories = $db->loadAssoc($db->setQuery("SELECT SQL_CACHE * FROM categories"));

cached 保留在内存中,直到服务器重新启动或您强制清除内存。

$db->query("RESET QUERY CACHE;");
于 2013-05-29T06:51:28.593 回答