Yii2 配置yii2redis扩展

前提:已经安装Redis

yii2配置yii2-redis扩展,有两种方式:包文件安装与composer安装,推荐composer方式安装。

一、包文件安装

下载redis包,https://github.com/yiisoft/yii2-redis,并放在vender/yiisoft/下, 
目录结构为:

yiisoft
    yii2-redis
    ...
extentions.php

  然后配置vender/yiisoft/extensions.PHP文件

'yiisoft/yii2-redis' => 
    array (
      'name' => 'yiisoft/yii2-redis',
      'version' => '2.0.5.0',
      'alias' => array (
         '@yii/redis' => $vendorDir . '/yiisoft/yii2-redis',
      ),
),

  

二、composer安装

composer安装, 在composer.json的require下加入:

"yiisoft/yii2-redis": "~2.0.0"

  然后执行

composer update

  两种方式安装完成后,就可以在yii2框架的配置文件中进行配置了。

#在config下的main.php 中component中修改cache配置:

'components' => [
   'cache' => [
#   'class' => 'yii\caching\FileCache',
      'class' => 'yii\redis\Cache',  //redis接管缓存
    ],
    'redis' => [
       'class' => 'yii\redis\Connection',
       'hostname' => 'localhost',
       'port' => 6379,
       'database' => 0,
    ],
],

  测试

Yii::$app->cache->set('test', 'hehe..');
echo Yii::$app->cache->get('test'), "\n";

  测试时会报错,访问无权限

Redis error: ERR operation not permitted Redis command was: SELECT 0

  修改方法

/etc/redis.conf
#注释下面一行
#requirepass 

  

原文地址:https://www.cnblogs.com/zheart/p/6631727.html