如何缓存有mysql查询的PHP页面。任何一个例子都是很好的,也是有帮助的。
发布于 2013-04-29 18:00:11
我使用的是phpFastCache (用于共享主机,如果你不想使用php.ini和root来设置memcached)。查看示例菜单。他们有完整详细的例子,而且非常简单。
首先使用phpFastCache::set进行设置,然后使用phpFastCache::get - DONE进行获取!
示例:减少数据库调用
您的网站有10,000名在线访问者,而您的动态页面在每次加载页面时都必须向数据库发送10,000个相同的查询。使用phpFastCache,您的页面只向DB发送一个查询,并使用缓存为9999个其他访问者提供服务。
<?php
// In your config file
include("php_fast_cache.php");
phpFastCache::$storage = "auto";
// you can set it to files, apc, memcache, memcached, pdo, or wincache
// I like auto
// In your Class, Functions, PHP Pages
// try to get from Cache first.
$products = phpFastCache::get("products_page");
if($products == null) {
$products = YOUR DB QUERIES || GET_PRODUCTS_FUNCTION;
// set products in to cache in 600 seconds = 5 minutes
phpFastCache::set("products_page",$products,600);
}
OUTPUT or RETURN your $products
?>
发布于 2010-09-24 20:57:38
我更喜欢使用缓存反向代理,比如Varnish。
就纯PHP解决方案而言,您可以在脚本末尾编写一些代码来缓存最终输出,在脚本开头编写代码来检查页面是否被缓存。如果在缓存中找到该页,则发送该页并退出,而不是再次运行查询。
<?php
function cache_file() {
// something to (hopefully) uniquely identify the resource
$cache_key = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']);
$cache_dir = '/tmp/phpcache';
return $cache_dir . '/' . $cache_key;
}
// if we have a cache file, deliver it
if( is_file( $cache_file = cache_file() ) ) {
readfile( $cache_file );
exit;
}
// cache via output buffering, with callback
ob_start( 'cache_output' );
//
// expensive processing happens here, along with page output.
//
function cache_output( $content ) {
file_put_contents( cache_file(), $content );
return $content;
}
显然,这需要对您的设置进行大量定制,包括缓存过期、满足您需求的$cache_key
以及错误检测,这样就不会缓存坏页面。
发布于 2010-09-24 20:48:51
memcache你的html,然后做类似这样的事情:
$memcache = memcache_connect('localhost', 11211);
$page = $memcache->get('homepage');
if($page == ""){
$mtime = microtime();
$page = get_home();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
memcache_set($memcache, 'homepage', $page, 0, 30);
$page .= "\n<!-- Duly stored ($totaltime) -->";
}
else{
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
$page .= "\n<!-- served from memcache ($totaltime) -->";
}
die($page);
https://stackoverflow.com/questions/3787125
复制相似问题