数据缓存是
将某些数据(一般是查询的结果集)进行缓存,它是最常用的一种缓存方式,一般采用memcache或apc作为缓存介质。
这里以 Yii 2.0 高级版为例,介绍如何使用 Yii 的数据缓存机制(一般用 memcache 作为缓存介质),将及时性要求不高的数据缓存起来,提高页面的响应速度。
首先,修改数据库配置文件
/advanced/common/config/main-local.php,内容如下:
[
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => 'basic_', // 表前缀
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
],
];
再来修改组件配置文件
/advanced/common/config/main.php,设置 memcache 缓存介质,内容如下:
dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\MemCache',
'keyPrefix' => 'advanced_', // key 的前缀
'servers' => [ // 可配多个memcache服务器,分布式
[
'host' => '127.0.0.1',
'port' => 11211,
'weight'=> 100, //权重,即访问该memcache服务器的概率
],
],
],
],
];
然后,在前台模型层
/advanced/frontend/models 中新建一个模型文件 User.php,内容如下:
select('*')
->from('{{%user}}')
->createCommand()
->queryAll();
return $res;
}
}
最后,在前台控制器层
/advanced/frontend/controllers 中新建一个控制器 CacheController.php ,用于测试,内容如下:
cache->delete($key); // 如果user表有写操作,就删除缓存,以便更新缓存
$userList = \Yii::$app->cache->get($key); // 读取缓存
if ($userList===false) { // 如果缓存不存在
echo '从数据库中读取数据!'.'
';
$userList = (new User())->getList(); // 从数据库中查询数据
$end = microtime(true);
\Yii::$app->cache->set($key, $userList, 10); // 写入缓存,过期时间为10秒,0表示永不过期
} else {
echo '从缓存中读取数据!'.'
';
$end = microtime(true);
}
echo $end-$start.'
'; // 查看读取数据所有的时间
var_dump($userList);
// 缓存的操作,常用的方法,除了set、get、delete外,还有mset、mget、flush。
// 缓存介质类的基类文件为 vendor/yiisoft/yii2/caching/Cache.php,如有必要,可以对其进行二次封装,如新建一个CacheHelper.php
}
}
?>
在浏览器中,访问
http://yii.frontend.com/?r=cache/index,查看测试的效果。