简体   繁体   中英

Use Redis and MongoDB ActiveRecords together in Yii2

I have MongoDB Active Records (models) and I'm wondering if it's possible to use Redis to automatically set/get/delete the models from Redis's storage.

For example, if I was to run:

MyModel::find()->where(["id" => 1])->one();

is there a way to make Redis store the result and return it the next time I run that same code?

Also, if I was to update the model with id = 1 , I'd expect Redis to invalidate the cache.

Is all that possible?

It doesn't matter which DB to use. It is about how to implement them. Yii have those two components to set in the config file:

The good thing about MongoDB and Redis is that both can be used as a database connection or as a cache component. You may have those configs for example:

'components' => [

    'db' => [
        'class' => '\yii\mongodb\Connection',
        'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
    ],

    'cache' => [
        'class' => 'yii\redis\Cache',
        'redis' => [
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ]
    ],
],

Here, while MongoDB is set as your default database, Redis is only used as a cache component and because all cache components have the same base class yii\\caching\\Cache they only support those APIs . Which should be fine if you are using it for caching proposes only.

Check the Yii2 Caching Guide to see all what you can do with a cache component. A quick example of what you are trying to do may be seen within @Blizz answer here where he did set an SQL query as a dependency to check if cached data should be used or invalidated instead.

In case you need to use the Redis database for more than just caching then you may have those configs instead:

'components' => [

    'mongodb' => [
        'class' => '\yii\mongodb\Connection',
        'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
    ],

    'redis' => [
        'class' => 'yii\redis\Connection',
        'hostname' => 'localhost',
        'port' => 6379,
        'database' => 0,
    ],

    'cache' => [
        'class' => 'yii\redis\Cache',
        'redis' => 'redis' // id of the connection application component
    ],

],

Here we defined 2 databases and selected one of them to be also used as a cache component. It should work the exact same way except that you can also use the Redis database inside your app as a Redis ActiveRecord or a Redis ActiveQuery class. You will just need to set which DB to be used inside each model class as it is done in this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM