yii2 redis错误:Database Exception – yii\db\Exception:Redis error: NOAUTH Authentication required.

  1. 问题

当使用yii2框架时,需要使用redis操作,在main.php,main-local.php中可配置redis相关数据,如下所示:

main.php中redis相关配置

 'cache' => [
    'class' => 'yii\redis\Cache',
    'redis' => [
        'hostname' => '192.168.1.1111',
        'port' => 6389,
        'database' => 0,
        'password' => '123456'
    ],
],

main-local.php中redis相关配置

 'cache' => [
    'class' => 'yii\redis\Cache',
    'redis' => [
        'hostname' => '192.168.1.1111',
        'port' => 6389,
        'database' => 0,
        'password' => 'xxxxx'
    ],
],

main-local.php中的cache配置会覆盖main.php中的cache配置,这时运行项目,可能会出现错误:

Redis error: NOAUTH Authentication required.
  1. 错误原因分析以及解决办法

(1).配置是否正确

可能是因为main-local.php中对应的redis配置错误导致的,检查对应的reids配置:hostname,port,database,以及password是否配置正确

解决办法:

再次确认redis配置是否正确,检查完毕后重新启动redis程序,并重新访问项目,看看结果如何

(2).redis是否启动

检查redis是否启动,是否可以进入redis服务端

解决办法:

下载reids-server, redis-cli,启动reids-server后,运行命令: redis-cli -h {ip} -p {端口} -a{密码}, 看看是否能够进入redis

(3).密码不合法

有这么个问题: 当项目在线上运行时,使用的是 云服务的redis时,有的云服务redis只能在 对应的内网访问(比如: 亚马逊aws),并且 没有密码(因为只能在内网访问,故aws开启redis时,没有密码),只能通过提供的 终端节点进行配置访问,所以,在项目配置的时候,就没有配置密码,如下:

main-local.php中redis相关配置

 'cache' => [
    'class' => 'yii\redis\Cache',
    'redis' => [
        'hostname' => 'xxx', //亚马逊aws redis终端节点
        'port' => 6389,
        'database' => 0,
        //'password' => '',  // 不配置密码,或者密码为空
    ],
],

这时,访问项目,出现:

Redis command was: AUTH 123456
出现这样的原因是: main.php中对应的redis配置中的password为123456,覆盖了main-local.php中的password, 为什么会这样呢?这是因为:在yii2的入口文件index.php中,使用的是
yii\helpers\ArrayHelper::merge()函数

入口文件index.php代码:

<?php

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';

$config = yii\helpers\ArrayHelper::merge(
    require __DIR__ . '/../../common/config/main.php',
    require __DIR__ . '/../../common/config/main-local.php',
    require __DIR__ . '/../config/main.php',
    require __DIR__ . '/../config/main-local.php'
);

(new yii\web\Application($config))->run();
它会将main.php中存在的属性在main-local.php中 覆盖,但是,如果一个数组中不存在的key,它会直接增加,如果key对应的值为空,则会使用main.php中对应key的值,这时最终的配置是'password' => '123456',使用的是main.php中的'password'

解决办法:

在main.php配置中, 删除 password这一项就可以啦

猜你喜欢

转载自blog.csdn.net/zhoupenghui168/article/details/131324327
今日推荐