在yii2应用程序中同时使用mysql和redis

iih3973s  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(343)

我正在构建一个crm系统,它应该允许不同的用户进行不同的访问,所以我需要在面板中进行复杂的身份验证和通知。但是主系统应该使用redis。我已经安装了yii2 redis插件,在db.php(mysql config)中有这样的配置:

<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2basic',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
    // Schema cache options (for production environment)
    //'enableSchemaCache' => true,
    //'schemaCacheDuration' => 60,
    //'schemaCache' => 'cache',
];

在web.php中:

$db = require __DIR__ . '/db.php';
$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],

'components' => [
        'redis'         => [

            'class'    => 'yii\redis\Connection',

            'hostname' => 'localhost',

            'port'     => 6379,

            'database' => 0,

        ],
     ],
     'db' => $db,

我如何区分我的模型,使用mysql还是redis?我假设如果在components部分指定redis,那么整个应用程序都使用redisdb。我可以使用redis来设置多个key值,但是由于redis会在达到最大内存时删除key,所以所有注册的用户和他们的配置文件都会被删除,所以我认为我应该使用mysql来实现basci的功能(带有角色、身份验证、配置文件的数据库)

tmb3ates

tmb3ates1#

return [
   'components' => [
      'db1' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db1name', //maybe other dbms such as psql,...
        'username' => 'db1username',
        'password' => 'db1password',
    ],
    'db2' => [
        'class' => 'yii\redis\Connection',
        'dsn' => 'YOURCONFIG', 
        'port' => '6379',
        'password' => 'db2password',
        'username' => 'db2username',
    ],
  ],
];

然后试着用

// To get from db1
Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll()

// To get from db2
Yii::$app->db2->createCommand((new \yii\db\Query)->select('*')->from('tbl_name'))->queryAll();

对于模型中的活动记录,请编写

// db1
public function getDb() {
    return Yii::$app->db1;
}

//Or db2
public function getDb() {
    return Yii::$app->db2;
}

相关问题