Redis | database | Yii Chinese document 2.0.x

Posted by zeodragonzord on Sun, 06 Feb 2022 20:32:40 +0100

Redis

The Yii2 redis extension provides support for the Yii2 framework redis Key value storage support. It contains a Cache and Session storage handle, and implements the ActiveRecord mode, which allows you to store activity records into redis.

install

demand

Redis version 2.6.12 is necessary for all components to work properly.

Get Composer installation package

The preferred way to install this extension is through composer.

Can run

php composer.phar require --prefer-dist yiisoft/yii2-redis

Or add

"yiisoft/yii2-redis": "~2.0.0"

In composer JSON file.

Configure application

When using this extension, you need to configure the [[yii\redis\Connection|Connection]] class in your application configuration:

return [
    //....
    'components' => [
        'redis' => [
            'class' => 'yii\redis\Connection',
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ],
    ]
];

Use of activity records

For general information on how to use yii's activity records, see guide.

Define a redis activity record class. Your record class needs to inherit from yii\redis\ActiveRecord and implement at least the attributes() method to define the attributes of the record. A primary key with no default value specified and id by default can be defined through [[yii\redis\ActiveRecord::primaryKey()]]. The primary key is a necessary part of the attribute, so please make sure you have an id attribute defined. If you don't specify your own primary key.

The following is a Customer instance model:

class Customer extends \yii\redis\ActiveRecord
{
    /**
     * @return array List of properties for this record
     */
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }

    /**
     * @return ActiveQuery Define a record associated with Order (it can be in other databases, such as elastic search or sql)
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }

    public static function find()
    {
        return new CustomerQuery(get_called_class());
    }
}

class CustomerQuery extends \yii\redis\ActiveQuery
{
    /**
     * Define a modified range of ` $query 'and return valid (status = 1) customers.
     */
    public function active()
    {
        return $this->andWhere(['status' => 1]);
    }
}

The general usage of redis activity records is very similar to that of database activity records, as shown in guide Described in. It supports the same interface and functions, except for the following limitations:

  • Since redis does not support SQL queries, the query API is limited to the following methods: where(), limit(), offset(), orderBy() and indexBy(). (orderBy() not implemented yet: #1305)
  • Because there is no table in redis, the relationship cannot be defined through the via table. You can only define relationships through other records.

In addition, you can also define the relationship from redis activity records to ordinary activity records, and vice versa.

Usage example:

$customer = new Customer();
$customer->attributes = ['name' => 'test'];
$customer->save();
echo $customer->id; // If not explicitly set, the id will be incremented automatically

$customer = Customer::find()->where(['name' => 'test'])->one(); // Find through query
$customer = Customer::find()->active()->all(); // Find all through query (use 'active' range)

Use the command line directly

Redis has many useful commands that can be used directly from the connection. After configuring the application, such as install As shown in, the connection can be obtained as follows:

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

After completion, you can execute the following commands. The most common method is to use the executeCommand method:

$result = $redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']);

Each command has corresponding shortcut support, so you can replace the above commands as follows:

$result = $redis->hmset(['test_collection', 'key1', 'val1', 'key2', 'val2']);

The list of available commands and their parameters can be found in redis.io/commands.

Use of cache components

To use Cache components, such as install As described in the chapter, in addition to configuring connections, you also need to configure cache components in [[yii\redis\Cache]]:

return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'yii\redis\Cache',
        ],
    ]
];

If you only use redis caching (that is, you don't use its activity records or sessions), you can also configure the connection parameters in the caching component (in this case, you don't need to configure the component connecting to the application):

return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'yii\redis\Cache',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];

Use of session components

In order to use the Session component, such as install As described in the chapter, in addition to configuring the connection, you also need to configure the session component in [[yii\redis\Session]]:

return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'yii\redis\Session',
        ],
    ]
];

If you only use redis session (that is, you do not use its activity record or cache), you can also configure the connection parameters in the session component (in this case, you do not need to configure the component connecting to the application):

return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'yii\redis\Session',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];

💖 Those who like this document are welcome to like, collect, leave a message or forward it. Thank you for your support! Author email: zhuzixian520@126.com

This article was first published in LearnKu.com On the website.