您的位置:首页 > 数据库 > Redis

Yii2-redis

2016-05-09 11:05 375 查看
安装:composer require --prefer-dist yiisoft/yii2-redis
redis 版本 >= 2.6.12

添加配置:

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


# ActiveRecord

继承自 \yii\redis\ActiveRecord 且必须实现 attributes() 方法

static active 方法 用来指定 查询条件

用法与自带的 ActiveRecord 相似 有以下不同

1、不支持SQL查询API 仅支持 where() limit() offset() orderBy() indexBy() (orderBy()暂未实现)

2、不能通过表来定义关系 redis中没有表

使用示例

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

/**
* @return ActiveQuery defines a relation to the Order record (can be in other database, e.g. elasticsearch or sql)
*/
public function getOrders()
{
return $this->hasMany(Order::className(), ['customer_id' => 'id']);
}

/**
* Defines a scope that modifies the `$query` to return only active(status = 1) customers
*/
public static function active($query)
{
$query->andWhere(['status' => 1]);
}
}

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

$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query
$customer = Customer::find()->active()->all(); // find all by query (using the `active` scope)


# 使用命令

$redis = Yii::$app->redis;
$result = $redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']); //通用用法
$result = $redis->hmset('test_collection', 'key1', 'val1', 'key2', 'val2');//方法用法


可用命令及参数 参考 http://redis.io/commands.

#缓存组件

配置

'components' => [
// ...
'cache' => [
'class' => 'yii\redis\Cache',
'redis' => [    // 如果只用作缓存  需要配置此项
'hostname' => 'localhost',
'port' => 6379,
'database' => 0,
],
],
]


# SESSION

配置

'components' => [
// ...
'session' => [
'class' => 'yii\redis\Session',
'redis' => [ //如果只用作 session 需要配置
'hostname' => 'localhost',
'port' => 6379,
'database' => 0,
],
],
]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: