How Magento cache Blocks HTML output

我曾错误地认为 Magento 安装后,只要启用 cache,Magento 就会缓存页面的大部分内容,比如,cms, product, category 的 content block。

直到今天第 N 遍看 Magento wiki,才意识到 Magento 初始只启用了很小一部分 block cache。细想之下,Magento 默认不缓存 content block 有一定的道理:各用户对内容缓存的要求不一而足,所以 Magento 把这个问题留给用户自己去思考。

Block cache 有三个参数,cache_lifetime 顾名思义,cache_tags 关系到 cache 何时更新,cache_key 关系到 cache 有多少个版本。

在 Magento 目录下所有文件里搜索 cache_tags 这个词,我只发现它只出现在跟 Navigation (产品菜单),Footer (脚注),Adminhtml Menu (后台菜单) 相关的少数文件里。由此说明 Magento 根本没有缓存页面的最主要部分:content block。我联想到很久以前我在 Magento forum 上提问的一个问题:为什么 cache 只用掉了 0.5 MB 内存?当时我用的是memcached,结果热心人来问我 memcached 有没有安装正确啊,php-perl-memcache 有没有安装啊。就是没有人告诉我——一切正常,因为 Magento 尚未缓存页面主要内容

了解了 Magento cache 机制,再根据自己的实际情况对 product page 缓存 content block 就简单了:只要在 extends Mage_Catalog_Block_Product_View 的基础上加入

    protected function _construct()
    {
        $this->addData(array(
            'cache_lifetime'    => 86400,  //seconds
            'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG . "_" . $this->getProduct()->getId()),
            'cache_key'         => $this->getProduct()->getId(),
        ));
    }

以此类推 cms page content block cache。Category page content block cache 稍微复杂一些,具体去看 Magento wiki。

设置 content block cache 对速度优化效果显著,我的 product page requests per second 指标提高了约 70%。

但我还是想让 Magento 跑得再快些,常说的那些 Magento 速度优化结果让我感觉不够畅快淋漓。我有个 page cache 想法,就是把整个页面缓存下来。Nginx 或其他的 web server 都有很好的机制去调度 html cache。据我测试,同一个静态内容的页面,保存为 html (Nginx 直接读取) 比保存为 php (经 php backend on socket or port 读取) 就快好几倍,这个结果让我对 page cache 充满了憧憬。

如使用 page cache,必须对页面中的 dynamic block (如 sidebar cart,recent viewed/compared products, etc)进行改写,简言之就是 load pages in two stages by ajax。Magento Enterprise Edition 就有 page cache feature,但我不清楚它是不是跟我同个思路。

与其买个 Magento Enterprise Edition,不过自己动手或请人实现 page cache。如果你恰好跟我有同样想法,请留言。

8 comments

  1. No. You haven’t.

    你未修改 sidebar 动态内容(包括 sidebar shopping cart 的内容),以致所有用户访问同一个页面时,看到 sidebar 的内容千篇一律。我猜你大概只是在 page block 上添了 cache_key,如果事情真是那么简单的话,Magento 发布时为什么不默认设置好整页缓存呢?如果事情真是那么简单的话,在 web server 上启用 html 缓存岂不更快?

    题外话:我看了你的网站,开了整页缓存速度还不够快,我的网站只在某些可以被缓存 child blocks 上启用 block 缓存,也比你快不少。建议你先看看有什么其他的提速方法先,或许升级服务器。

  2. 你好,向你请教一个问题:http://www.magentocommerce.com/wiki/5_-_modules_and_development/block_cache_and_html_ouput
    商品页分类页缓存具体是怎么做的?修改哪个文件?

  3. 找插件实现这个了:http://www.magentocommerce.com/magento-connect/utilities/server-performance-caching/made-cache-9281.html

  4. 以前没注意到 “High Performance Cache with Varnish support” 这个插件,现在没时间测试它。不过,看它介绍,没有 full page cache 功能。无非多缓存了几个 Magento 自身不缓存的 block,这也无法实质性(指数级)提高访问速度。

Leave a comment

Your email address will not be published. Required fields are marked *