我编写了第一个名为Heater的功能性PHP webapp.它使用Google Charts库和AWS Redshift backend呈现交互式日历热图.
现在我已经开始工作了,我已经开始提高性能了.我已经安装了APC并验证它正在运行.
我的问题是如何在Redshift前启用查询缓存?
这是我现在如何加载数据的示例:
getRsData.php:
<?php
$id=$_GET["id"];
$action=$_GET["action"];
$connect = $rec = "";
$connect = pg_connect('host=myredshift.redshift.amazonaws.com port=5439 dbname=mydbname user=dmourati password=mypasword');
if ($action == "upload")
$rec = pg_query($connect,"SELECT date,SUM(upload_count) as upload_count from dwh.mytable where enterprise_id='$id' GROUP BY date");
...
?>
一些查询采取> 5秒会对用户体验产生负面影响.数据移动缓慢,因为它每天只更新一次.我想用一个本地APC缓存来处理Redshift查询,然后每天一次通过cron(或其他一些)使它无效,以允许更新的数据流入.我最终想创建一个缓存加温脚本但是这在当时是不必要的.
任何有关文档的指针或提示都很有帮助.我花了一些时间谷歌搜索,但大多数文档只是文档缓存而不是查询缓存,如果这是有道理的.这是一个运行AWS Linux和PHP 5.3的独立主机,带有apc-3.1.15.
谢谢.
编辑以添加输入验证
if (!preg_match("/^[0-9]*$/",$id)) {
$idErr = "Only numbers allowed";
}
if (empty($_GET["action"])) {
$actionErr = "Action is required";
} else {
$action = test_input($action);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
解决方法:
这似乎不需要APC,因为你要缓存一天相对较长的数据.
下面的代码将您的查询结果缓存在一个文件($cache_path)中.在查询redshift之前,它会检查给定企业ID的缓存文件是否存在并在同一天创建.如果确实如此,并且代码可以成功检索缓存,则从缓存返回行,但如果文件不存在或无法从缓存中检索行,则代码将查询db并写入缓存.
查询/缓存的结果以$rows的形式返回
<?php
$id=$_GET["id"];
$action=$_GET["action"];
$connect = $rec = "";
$connect = pg_connect('host=myredshift.redshift.amazonaws.com port=5439 dbname=mydbname user=dmourati password=mypasword');
if ($action == "upload") {
$cache_path = "/my_cache_path/upload_count/$id";
if(!file_exists($cache_path)
|| date('Y-m-d',filemtime($cache_path)) < date('Y-m-d')
|| false === $rows = unserialize(file_get_contents($cache_path))) {
$rows = array();
$rec = pg_query($connect,"SELECT date,SUM(upload_count) as upload_count from dwh.mytable where enterprise_id='$id' GROUP BY date");
while($r = pg_fetch_assoc($rec)) {
$rows[] = $r;
}
file_put_contents($cache_path,serialize($rows));
}
}
?>