Add redis cache to the project
1.composer installs redis
composer require "yiisoft/yii2-redis"
2. Settings in the project configuration file: import cache and link redis server
common/config/main.php:
'components' => [ 'cache' => [ // 'class' => 'yii\caching\FileCache', 'class' => \yii\redis\Cache::class, 'redis' => 'redis' ], ]
Common / config / main local.php: link redis server
'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => '10.110.XX.XX',//server address 'port' => 6379, 'database' => 0, ],
3. Use of cache
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('Menu does not exist'); } return get_tree($menus); },3600 * 24); }
4. Clear cache
A. create a clearly cached class
<?php namespace common\behaviors; use yii\base\Behavior; use yii\base\Event; use yii\db\ActiveRecord; use common\contracts\ShouldClearCache; /** * Clear Redis cache * 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' ]; } /** * Clear cache * @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. create an interface to clear the cache
<?php namespace common\contracts; // Need to clear cache interface ShouldClearCache { public function cacheKeys(); }
c. clear cache when adding, editing and deleting backend
Note: model To inherit an interface implements ShouldClearCach public function cacheKeys() { return [ YII_ENV.':templateMenu:'.$this->template_enum, //Key names to clear ]; } public function behaviors() { return array_merge(parent::behaviors(), [ 'class' => CacheClearBehavior::class, ]); }
Note: if the cache cannot be cleared, first check whether the key name is the same, whether the same redis server is connected, and whether it is cleared in this model