定期使用查询填充视图数据

时间:2011-12-02 14:13:48

标签: php mysql caching

我正在编写一个包含每日/每周/每月报告数据的视图。我认为仅定期运行查询来更新数据而不是在有人加载页面时命中数据库是有意义的。这可以在PHP和MySQL中完全完成吗?什么是一些有效的方法来处理这个?

4 个答案:

答案 0 :(得分:1)

使用支持缓存的Smarty等模板引擎,可以为这些页面设置较长的缓存时间。然后,您需要对PHP进行编码以测试日期约束是否已更改以及数据是否尚未缓存,如果其中任何一个条件为真,请执行查询。否则,Smarty将只加载缓存页面,您的代码将不会查询数据库。

$smarty = new Smarty();
if (!$smarty->isCached('yourtemplate.tpl')) {
  // Run your query and populate template variables
}
$smarty->display('yourtemplate.tpl');

Further documentation on Smarty caching

答案 1 :(得分:1)

是但不是很好。您想查看Cron作业,大多数Web主机提供设置Crons的服务。它们只是运行脚本,任何脚本,PHP,Javascript,整页等的一种方式。

搜索谷歌的cron作业,你应该找到你想要的东西。

如果您的Web主机不提供cron作业而您不知道Unix命令如何工作,那么有些站点将为您托管一个cron作业。

结帐

http://www.cronjobs.org/

答案 2 :(得分:1)

  

我认为仅定期运行查询来更新数据而不是在有人加载页面时命中数据库是有意义的

就个人而言,我会同时选择。 e.g。

SELECT customer, COUNT(orders.id), SUM(order_lines.value)
FROM orders, order_lines
WHERE orders.id=order_lines.order_id
AND orders.placed>@last_time_data_snapshotted
AND orders.customer=@some_user
GROUP BY customer
UNION
SELECT user, SUM(rollup.orders), SUM(rollup.order_value)
FROM rollup
WHERE rollup.last_order_date<@last_time_data_snapshotted
AND rollup.customer=@some_user
GROUP BY customer
  

而不是在有人加载页面时点击数据库

实际上,根据使用模式,这可能很有意义。但这并不一定排除上述方法 - 只需在将聚合数据推送到预合并表并在每个请求上测试阈值时设置阈值。

答案 3 :(得分:1)

我个人会将缓存的数据存储在一个文件中,然后只读取该文件,如果它已在特定时间范围内更新,如果没有则更新(例如从数据库获取信息,写入文件)。

一些示例代码:

$cacheTime = 900; // 15 minutes
$useCache = false;
$cacheFile = './cache/twitter.cachefile';
// check time
if(file_exists($cacheFile)){
    $cacheContents = file_get_contents($cacheFile);
  if((date('U')-filemtime($cacheFile))<$cacheTime || filesize($cacheFile)==0){
    $useCache = true;
  }
}
if(!$useCache){
  // get all your update data setting $cacheContents to the file output. I'd imagine using a buffer here would be a good idea.

  // update cache file contents
  $fh = fopen($cacheFile, 'w+');
  fwrite($fh, $cacheContents);
  fclose($fh);
}

echo $cacheContents;
相关问题