该教程已被合并到《Yii2 权威指南中文版》中!Yiichina 教程地址为《yii2-redis 扩展详解》!php
yii2-redis 扩展为 Yii2 框架提供了 redis 键值存储支持。包括缓存(Cache)、会话存储处理(Session),并实现了 ActiveRecord 模式,容许您将活动记录存储在 redis 中。html
在 Yii2 项目根目录,执行如下命令安装:git
$ composer require yiisoft/yii2-redis
也能够先在 composer.json 文件中声明以下依赖:github
"yiisoft/yii2-redis": "~2.0.0"
再执行下面命令安装:redis
$ composer update
继续阅读请确保已安装并开启了 redis 服务,安装请参考《Redis 安装》。sql
在组件中添加以下配置:数据库
'components' => [ 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ], ]
下面代码演示了 redis 最基本的 string 类型的使用:json
// 获取 redis 组件 $redis = Yii::$app->redis; // 判断 key 为 username 的是否有值,有则打印,没有则赋值 $key = 'username'; if ($val = $redis->get($key);) { var_dump($val); } else { $redis->set($key, 'marko'); $redis->expire($key, 5); }
这个类中(yii\redis\Connection
)提供了操做 redis 全部的数据类型和服务(String、Hash、List、Set、SortedSet、HyperLogLog、GEO、Pub/Sub、Transaction、Script、Connection、Server)所须要的方法,而且和 redis 中的方法同名,若是不清楚能够直接到该类中查看。缓存
该扩展中的 yii\redis\Cache
实现了 Yii2 中的缓存相关接口,因此咱们也能够用 redis 来存储缓存,且用法和原来同样。yii2
修改组件中 cache 的 class 为 yii\redis\Cache
便可,配置以下:
'components' => [ 'cache' => [ // 'class' => 'yii\caching\FileCache', 'class' => 'yii\redis\Cache', ], ],
若是没有配置过 redis 组件,须要在 cache 组件下配置 redis 服务相关参数,完整配置以下:
'components' => [ 'cache' => [ // 'class' => 'yii\caching\FileCache', 'class' => 'yii\redis\Cache', 'redis' => [ 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ], ], ],
下面代码演示了缓存的基本使用:
// 获取 cache 组件 $cache = Yii::$app->cache; // 判断 key 为 username 的缓存是否存在,有则打印,没有则赋值 $key = 'username'; if ($cache->exists($key)) { var_dump($cache->get($key)); } else { $cache->set($key, 'marko', 60); }
使用文件缓存(FileCache)时,缓存是存储在 runtime/cache 目录下;使用 redis 缓存后,缓存将存储在 redis 数据库中,性能将大大提升。
该扩展中的 yii\redis\Session
实现了 Yii2 中的会话相关接口,因此咱们也能够用 redis 来存储会话信息,且用法和原来同样。
修改组件 session 的配置,指定 class 为 yii\redis\Session
便可,配置以下:
'components' => [ 'session' => [ 'name' => 'advanced-frontend', 'class' => 'yii\redis\Session' ], ],
若是没有配置过 redis 组件,须要在 session 组件下配置 redis 服务相关参数,完整配置以下:
'components' => [ 'session' => [ 'name' => 'advanced-frontend', 'class' => 'yii\redis\Session', 'redis' => [ 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ], ], ],
在开发过程当中,切记必定不要使用 PHP 原生的 $_SESSION 去操做,而要使用 Yii 提供的 session 组件,获取方式以下:
$session = Yii::$app->session;
该扩展中的 yii\redis\ActiveRecord
实现了 Yii2 中的 ActiveRecord 相关接口,因此咱们可使用 AR 的方式操做 redis 数据库。关于如何使用 Yii 的 ActiveRecord,请阅读权威指南中有关 ActiveRecord 的基础文档。
定义 redis ActiveRecord 类,咱们的模型须要继承 yii\redis\ActiveRecord
,并至少实现 attributes()
方法来定义模型的属性。
主键能够经过 yii\redis\ActiveRecord::primaryKey()
定义,若是未指定,则默认为 id。 primaryKey 必须在 attributes() 方法定义的属性中,若是没有指定主键,请确保 id 在属性中。
下面定义一个 Customer 模型来演示:
class Customer extends \yii\redis\ActiveRecord { /** * 主键 默认为 id * * @return array|string[] */ public static function primaryKey() { return ['id']; } /** * 模型对应记录的属性列表 * * @return array */ public function attributes() { return ['id', 'name', 'age', 'phone', 'status', 'created_at', 'updated_at']; } /** * 定义和其它模型的关系 * * @return \yii\db\ActiveQueryInterface */ public function getOrders() { return $this->hasMany(Order::className(), ['customer_id' => 'id']); } }
使用示例:
// 使用 AR 方式新增一条记录 $customer = new Customer(); $customer->name = 'marko'; $customer->age = 18; $customer->phone = 13888888888; $customer->status = 1; $customer->save(); echo $customer->id; // 使用 AR 查询 $customer = Customer::findOne($customer->id); $customer = Customer::find()->where(['status' => 1])->all();
redis ActiveRecord 的通常用法与权威指南中数据库的 ActiveRecord 用法很是类似。它们支持相同的接口和方法,除了如下限制:
直接使用 redis 链接,就可使用 redis 提供的不少有用的命令。配置好 redis 后,用如下方式获取 redis 组件:
$redis = Yii::$app->redis;
而后就能够执行命令了,最通用的方法是使用 executeCommand 方法:
$result = $redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']);
支持的每一个命令都有一些快捷方式,能够按照以下方式使用:
$result = $redis->hmset('test_collection', 'key1', 'val1', 'key2', 'val2');
有关可用命令及其参数的列表,请参阅 redis 命令:
本文首发于马燕龙我的博客,欢迎分享,转载请标明出处。
马燕龙我的博客:http://www.mayanlong.com
马燕龙我的微博:http://weibo.com/imayanlong
马燕龙Github主页:https://github.com/yanlongma