前提:已經安裝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