15. Yii 2.0 页面缓存

来源:互联网 发布:为什么要探索宇宙 知乎 编辑:程序博客网 时间:2024/06/06 01:04
页面缓存是将整个静态页面(一般是首页)进行缓存,也比较常用,一般采用 File 作为缓存介质。
页面缓存是将整个控制器方法的输出(整个页面),利用缓存介质缓存起来,页面缓存生效期间,改变指定方法(一般是缓存index方法)的输出,实际的输出并不会发生变化。

这里以 Yii 2.0 高级版为例,介绍页面缓存。

操作页面缓存的类文件为 /advanced/vendor/yiisoft/yii2/filters/PageCache.php

首先,修改组件配置文件 /advanced/common/config/main.php,注册一个不同的缓存组件 fcache,内容如下:
  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\MemCache', // memcache缓存介质,常用于数据缓存
'keyPrefix' => 'advanced_', // key 的前缀
'servers' => [ // 可配多个memcache服务器,分布式
[
'host' => '127.0.0.1',
'port' => 11211,
'weight'=> 100, //权重,即访问该memcache服务器的概率
],
],
],
'fcache' => [ // 注册一个不同的组件名称 fcache,用于和 cache 组件区分开来
'class' => 'yii\caching\FileCache', // 文件缓存介质,常用于页面缓存
]
],
];
 来自CODE的代码片
01.php
其次,我们在前台控制器层 /advanced/frontend/controllers 新建一个文件 PageCacheController.php 用于测试,内容如下:
  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
<?php
namespace frontend\controllers;
use yii\web\Controller;
use frontend\models\User;
class PageCacheController extends Controller {
/*
* 控制器中必须包含该方法,来实现页面缓存
*/
public function behaviors()
{
return [
// 页面缓存的配置
'pageCache' => [
'class' => 'yii\filters\PageCache',
'only' => ['index'], // 指定对哪个方法采用页面缓存,可配置多个
'duration' => 60, // 过期时间
'dependency' => [ // 缓存依赖,控制缓存失效的另外一种辅助方法
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT COUNT(*) FROM basic_user',
],
'variations' => [ // 根据语言的不同,生成多个缓存
\Yii::$app->language,
],
'cache' => 'fcache', // 页面缓存的缓存介质,指定使用文件缓存组件,默认值为 cache
'enabled' => !YII_DEBUG, // 是否启用页面缓存,一般debug模式下,我们会设置关闭页面缓存,部署到生产环境时,关闭了调试模式,就会使用页面缓存
],
];
}
/**
* index方法,采用页面缓存(用文件缓存介质,当然页面缓存也可以使用memcache缓存介质,但一般不这么使用)
* 本页面采用了页面缓存,就没有必要再使用数据缓存
*/
public function actionIndex(){
echo '页面缓存:'.microtime(true).'<br>';
}
/**
* 其他方法,采用数据缓存(一般用memcache作为缓存介质)
*/
public function actionDataCache(){
$key = 'userlist';
$start = microtime(true);
// \Yii::$app->cache->delete($key); // 如果user表有写操作,就删除缓存,以便更新缓存
$userList = \Yii::$app->cache->get($key); // 读取缓存
if ($userList===false) { // 如果缓存不存在
echo '从数据库中读取数据!'.'<br>';
$userList = (new User())->getList(); // 从数据库中查询数据
$end = microtime(true);
\Yii::$app->cache->set($key, $userList, 60); // 写入缓存,过期时间为10秒,0表示永不过期
} else {
echo '从缓存中读取数据!'.'<br>';
$end = microtime(true);
}
echo $end-$start.'<br>'; // 查看读取数据所有的时间
var_dump($userList);
}
}
 来自CODE的代码片
snippet_file_0.php
由于是测试,故就算是debug模式,我们也可以开启页面缓存,将  'enabled'    => !YII_DEBUG 中的感叹号去掉即可。

最后,在浏览器中输入 http://yii.frontend.com/?r=page-cache/index 测试页面缓存,输入 http://yii.frontend.com/?r=page-cache/data-cache 可测试数据缓存。
原创粉丝点击