如何缓存动态 PHP 页面

20
如何缓存包含MySQL查询的PHP页面。 有任何示例都将非常有帮助。

您想要集成HTTP缓存吗? - Gumbo
5个回答

18

我正在使用phpFastCache(适用于共享主机,如果您不想触及php.ini和root来设置memcached)。 查看示例菜单。他们有完整的详细示例,非常容易上手。

首先使用phpFastCache::set进行设置,然后使用phpFastCache::get进行获取 - 完成!

示例:减少数据库调用

您的网站有10,000个在线访问者,并且每次页面加载时,您的动态页面必须向数据库发送10,000个相同的查询。 使用phpFastCache,您的页面仅向数据库发送1个查询,并使用缓存为其他9,999个访问者提供服务。

<?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
?>

+1 的例子和适用于共享主机的示例。干杯! - Mario Awad
你如何使用这个类?你能回答我的问题吗?http://stackoverflow.com/questions/22116573/how-to-use-phpfastcache - Mohammad Fanni

13

我更倾向于使用缓存反向代理,例如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,以及错误检测,以避免不良页面被缓存。


你在哪里调用 cache_output 函数? - A F
1
@AakilFernandes 输出缓冲区在请求结束时会自动刷新。ob_start() 指定 cache_output() 作为其回调函数。因此,在结束时的隐式刷新会调用 cache_output() - Annika Backstrom

2
将您的 HTML 缓存到 memcache 中,然后执行以下操作:
$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&lt;!-- served from memcache ($totaltime) -->";
}
die($page);

2
    <?php
    //settings
    $cache_ext  = '.html'; //file extension
    $cache_time     = 3600;  //Cache file expires afere these seconds (1 hour = 3600 sec)
    $cache_folder   = 'cache/'; //folder to store Cache files
    $ignore_pages   = array('', '');

    $dynamic_url    = 'http://'.$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']; // requested dynamic page (full url)
    $cache_file     = $cache_folder.md5($dynamic_url).$cache_ext; // construct a cache file
    $ignore = (in_array($dynamic_url,$ignore_pages))?true:false; //check if url is in ignore list

    if (!$ignore && file_exists($cache_file) && time() - $cache_time < filemtime($cache_file)) { //check Cache exist and it's not expired.
        ob_start('ob_gzhandler'); //Turn on output buffering, "ob_gzhandler" for the compressed page with gzip.
        readfile($cache_file); //read Cache file
        echo '<!-- cached page - '.date('l jS \of F Y h:i:s A', filemtime($cache_file)).', Page : '.$dynamic_url.' -->';
        ob_end_flush(); //Flush and turn off output buffering
        exit(); //no need to proceed further, exit the flow.
    }
    //Turn on output buffering with gzip compression.
    ob_start('ob_gzhandler');
    ######## Your Website Content Starts Below #########
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <title>Page to Cache</title>
        </head>
            <body>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ut tellus libero.
            </body>
    </html>
    <?php
    ######## Your Website Content Ends here #########

    if (!is_dir($cache_folder)) { //create a new folder if we need to
        mkdir($cache_folder);
    }
    if(!$ignore){
        $fp = fopen($cache_file, 'w');  //open file for writing
        fwrite($fp, ob_get_contents()); //write contents of the output buffer in Cache file
        fclose($fp); //Close file pointer
    }
    ob_end_flush(); //Flush and turn off output buffering

    ?>

1
重要的事情,在讨论缓存时经常被忽视,是进程同步以避免线程竞争(参见:https://en.wikipedia.org/wiki/Race_condition)。
在没有同步的情况下,PHP中典型的缓存场景如下:如果您在缓存中没有资源,或者资源已过期,则必须创建并放入缓存中。首个遇到此类条件的线程/进程正在尝试创建资源,并且在此期间,其他线程也会创建资源,这导致线程竞争、缓存猛击和性能下降。
问题随着并发线程数和资源创建任务所创建的工作负载而变得更加严重。在繁忙的系统上,它可能导致严重问题。
PHP中很少有考虑同步的缓存系统。
其中之一是php-no-slam-cache:https://github.com/tztztztz/php-no-slam-cache

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接