yii2.0中redis的使用
程序员文章站
2024-03-22 10:50:40
...
项目中添加redis缓存
1.composer安装redis
composer require "yiisoft/yii2-redis"
2.项目配置文件中设置:引入cache和链接redis服务器
common/config/main.php:
'components' => [
'cache' => [
// 'class' => 'yii\caching\FileCache',
'class' => \yii\redis\Cache::class,
'redis' => 'redis'
],
]
common/config/main-local.php:链接redis服务器
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => '10.110.XX.XX',//服务器地址
'port' => 6379,
'database' => 0,
],
3.缓存的使用举例
public static function getMenus($templateEnum)
{
return \Yii::$app->cache->getOrSet(YII_ENV.':templateMenu:'.$templateEnum, function () use ($templateEnum) {
$menus = TemplateMenu::find()->select(['menu_id', 'template_enum', 'sort'])
->where(['template_enum' => $templateEnum])
->orderBy('sort')
->with('menu')
->asArray()
->all();
if (empty($menus)) {
throw new NotFoundHttpException('菜单不存在');
}
return get_tree($menus);
},3600 * 24);
}
4.清除缓存
a.创建清楚缓存的类
<?php
namespace common\behaviors;
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;
use common\contracts\ShouldClearCache;
/**
* 清空Redis缓存
* Class CacheClearBehaviors
* @package backend\Behaviors
*/
class CacheClearBehavior extends Behavior
{
public function events()
{
return [
ActiveRecord::EVENT_AFTER_DELETE => 'clear',
ActiveRecord::EVENT_AFTER_INSERT => 'clear',
ActiveRecord::EVENT_AFTER_UPDATE => 'clear'
];
}
/**
* 清除缓存
* @param Event $event
*/
public function clear(Event $event)
{
if ($event->sender instanceof ShouldClearCache) {
$keys = $event->sender->cacheKeys();
if (!is_array($keys)) {
$keys = [$keys];
}
if (!empty($keys)) {
foreach ($keys as $key) {
\Yii::$app->cache->delete($key);
}
}
}
}
}
b.创建清除缓存的接口
<?php
namespace common\contracts;
// 需要清除缓存
interface ShouldClearCache
{
public function cacheKeys();
}
c.后端添加,编辑,删除时清除缓存
注:model要继承接口 implements ShouldClearCach
public function cacheKeys()
{
return [
YII_ENV.':templateMenu:'.$this->template_enum, //要清除的键名
];
}
public function behaviors()
{
return array_merge(parent::behaviors(), [
'class' => CacheClearBehavior::class,
]);
}
注:如果缓存清不了的时候首先看键名是否一样,是否连接的是同一台redis服务器,是否是在此model里面清除的