Yii2 镜像一个数据库table到redis用于高速活动记录查询

Yii2 Mirror a database table to redis for high speed active record query

我想做的是将所有结果缓存在一个很少变化的MySQLtable中,从而最大限度地减少对数据库的调用并提高查询速度。那里大约有 10 万条记录。

是否有库可以同步这个table中所做的更改,比如更新或插入记录时,redis缓存也会失效并更新。

我见过一个用于 elasticsearch 的,但没有看到一个用于 redis 的。

从这个页面:

有这条评论:

You can get all models attributes by:

$data = $model->attributes; and assign them to another model

$anotherModel = new AnotherActiveRecord();

$anotherModel->setAttributes($data);

now another model will extract whatever it can from $data

我很好奇,Redis 缓存是否也能以类似的方式“镜像”数据库中的数据table?

或者这总体上是个坏主意,最好在查询出现时缓存它,或者有更好的方法。

您可以根据 https://www.yiiframework.com/doc/guide/2.0/en/caching-data

启用缓存
[
    'components' => [
        'cache' => [
            'class' => 'yii\redis\Cache',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ]
        ],
    ],
]

然后使用 Query Caching,它在查询构建器级别

上本地定义
$result = $db->cache(function ($db) {
    // the result of the SQL query will be served from the cache
    // if query caching is enabled and the query result is found in the cache

    // ... perform SQL queries here ...
});

您也可以根据您的 table 使用 Cache Dependencies(一些标准,例如 max(updated_at) 是否更改)。

// Create a dependency on updated_at field
$dependency = new yii\caching\DbDependency(['sql' => 'select max(updated_at) from my_table']);
$duration = 60;     // cache query results for 60 seconds.

$result = $db->cache(function ($db) {
    // ... perform SQL queries here ...

    return $result;
}, $duration, $dependency);