我已经写了我的第一个PHP web应用程序名为加热器。它使用Google Charts库和AWS Redshift后端呈现交互式日历热图。
现在我让它工作了,我已经开始提高性能了。我已经安装了APC并验证了它是工作的。
我的问题是如何在红移前启用查询缓存?
下面是我现在如何加载数据的一个例子:
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缓存来处理红移查询,然后每天一次通过cron(或一些这样的)使其无效,以允许更新的数据流入。我最终想创建一个缓存升温脚本,但目前没有必要。
任何指向文档的指针或提示都是有帮助的。我花了一些时间在谷歌上搜索,但大多数文档只是关于文档缓存,而不是查询缓存,如果有意义的话。这是一个独立的主机,运行AWS Linux和PHP 5.3, apc-3.1.15。谢谢。
EDIT添加输入验证
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的缓存文件是否存在并且是在同一天创建的。如果文件存在,并且代码可以成功检索缓存,则从缓存中返回行,但如果文件不存在或无法从缓存中检索行,代码将查询数据库并写入缓存。
查询/缓存的结果在$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));
}
}
?>
如果你不想要文件缓存,只需使用FastCache之类的缓存类
http://www.phpfastcache.com/它可以自动找到apc或任何其他缓存解决方案。
使用起来真的很容易
<?php
// In your config file
include("phpfastcache/phpfastcache.php");
phpFastCache::setup("storage","auto");
// phpFastCache support "apc", "memcache", "memcached", "wincache" ,"files", "sqlite" and "xcache"
// You don't need to change your code when you change your caching system. Or simple keep it auto
$cache = phpFastCache();
// In your Class, Functions, PHP Pages
// try to get from Cache first. product_page = YOUR Identity Keyword
$products = $cache->get("product_page");
if($products == null) {
$products = YOUR DB QUERIES || GET_PRODUCTS_FUNCTION;
// set products in to cache in 600 seconds = 10 minutes
$cache->set("product_page", $products,600);
}
// Output Your Contents $products HERE
?>
这个例子也来自http://www.phpfastcache.com/
希望它能有所帮助,并与你真正酷的项目玩得开心!