Yii2 + Redis 作为数据库

Yii2 + Redis as Database

我想使用Yii2和redis作为数据库。

到目前为止,我从这里得到了 Yii2 的 Redis ActiveRecord Class。

link1

link2

但是,我遇到了一个问题。为什么这个 CLASS 在 REDIS 中添加任何东西作为哈希????

以上我无法找到它插入数据的模式。我添加一个用户,它将在 user:xxx 命名空间下添加一个用户,在 s:user:xxx 下添加另一个记录,依此类推,但是主题的 none 具有我在属性中定义的任何字段!仅包含 ID。

我知道Key-value类型的数据库和RDBMS是不一样的,也知道在Redis中如何实现类似records的关系,但不知道为什么只保存ID

到目前为止我找不到任何使用 redis ActiveRecords 的例子。

这里有一个,但不够好。

所以这是我的主要问题:如何在 YII2 中使用 activeRecords 和不同的数据类型向 redis 添加数据?

如果 ActiveRecords 不可能,最好的解决方案是什么?在这种情况下

另一个问题:是否可以改用模型并编写我自己的 model::save() 方法?以这种速度,最好的数据验证解决方案是什么?

实际上我想制作一个电报机器人,所以我应该在 RabitMQ 中获取消息并发送它们,在 worker 中获取数据,进行处理并将结果保存到 Redis,最后通过 RabitMQ 将响应发送给用户。

所以我需要做很多验证和当然的身份验证并保存和 select 和范围并保存以设置列表和这个和那个....

我想要一个制作模型或活动记录的好方法或验证的正确解决方案,将数据保存和检索到 Redis 和 Yii2。

Redis DB 可以声明为缓存组件或数据库连接两者.

当它被声明为缓存组件时(使用yii/redis/cache) it is accessible within that component to store key/value pairs as shown here

$cache = Yii::$app->cache;

// try retrieving $data from cache
$data = $cache->get($key);
// store $data in cache so that it can be retrieved next time
$cache->set($key, $data);

// one more example:
$access_token = Yii::$app->security->generateRandomString();
$cache->add(
    // key
    $access_token, 
    // data (can also be an array)
    [
        'id' => Yii::$app->user->identity->id
        'name' => Yii::$app->user->identity->name
    ], 
    // expires
    60*60*3
);

其他组件也可能开始使用它来缓存建议,例如 session 如果配置为这样做或喜欢 yii\web\UrlManager which by default will try to cache the generated URL rules in whatever valid caching mechanism defined under the config file's cache component as explained here。所以在这种情况下找到一些不是你的存储数据是正常的。

当 Redis 被声明为 DB 连接 就像在您提供的链接中一样,这意味着使用 yii\redis\Connection class you can make your model extending its \yii\redis\ActiveRecord class 作为 Yii 中的任何其他 ActiveRecord 模型.到目前为止我知道的唯一区别是您需要手动定义您的属性,因为没有数据库模式可以为 NoSQL 数据库解析。然后只需像任何其他 ActiveRecord 模型一样定义您的规则、场景、关系、事件……:

class Customer extends \yii\redis\ActiveRecord
{
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }

    public function rules()
    {
        return [
            ['name', 'required'],
            ['name', 'string', 'min' => 3, 'max' => 12, 'on' => 'register'],
            ...
        ];
    }

    public function attributeLabels() {...}
    ...
}

所有可用的方法,包括 save()validate()getErrors()、...都可以找到 here and should be used like any other ActiveRecord class as shown in the official guide