Yii2 教程 - yii2-redis 扩展详解
该教程已被合并到《Yii2 权威指南中文版》中!Yiichina 教程地址为《yii2-redis 扩展详解》!
一、简介
yii2-redis 扩展为 Yii2 框架提供了 redis 键值存储支持。包括缓存(Cache)、会话存储处理(Session),并实现了 ActiveRecord 模式,允许您将活动记录存储在 redis 中。
相关链接
二、安装扩展
在 Yii2 项目根目录,执行以下命令安装:
$ composer require yiisoft/yii2-redis
也可以先在 composer.json 文件中声明如下依赖:
"yiisoft/yii2-redis": "~2.0.0"
再执行下面命令安装:
$ composer update
三、基本使用
继续阅读请确保已安装并开启了 redis 服务,安装请参考《Redis 安装》。
1. 配置
在组件中添加如下配置:
'components' => [
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => 'localhost',
'port' => 6379,
'database' => 0,
],
]
2. 示例
下面代码演示了 redis 最基本的 string 类型的使用:
// 获取 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 来存储缓存,且用法和原来一样。
1. 配置
修改组件中 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,
],
],
],
2. 示例
下面代码演示了缓存的基本使用:
// 获取 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 来存储会话信息,且用法和原来一样。
1. 配置
修改组件 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,
],
],
],
2. 使用
在开发过程中,切记一定不要使用 PHP 原生的 $_SESSION 去操作,而要使用 Yii 提供的 session 组件,获取方式如下:
$session = Yii::$app->session;
六、ActiveRecord
该扩展中的 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 不支持 sql,查询方法仅限于使用以下方法:where(),limit(),offset(),orderBy() 和 indexBy()。 【 orderBy() 尚未实现:#1305)】
- 由于 redis 没有表的概念,因此不能通过表定义关联关系,只能通过其它记录来定义关系。
七、直接使用命令
直接使用 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
Yii2 教程 - yii2-redis 扩展详解的更多相关文章
- [js高手之路] es6系列教程 - 对象功能扩展详解
第一:字面量对象的方法,支持缩写形式 //es6之前,这么写 var User = { name : 'ghostwu', showName : function(){ return this.nam ...
- 七牛云存储Python SDK使用教程 - 上传策略详解
文 七牛云存储Python SDK使用教程 - 上传策略详解 七牛云存储 python-sdk 七牛云存储教程 jemygraw 2015年01月04日发布 推荐 1 推荐 收藏 2 收藏,2.7k ...
- python操作redis用法详解
python操作redis用法详解 转载地址 1.redis连接 redis提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,并使用 ...
- redis配置详解
##redis配置详解 # Redis configuration file example. # # Note that in order to read the configuration fil ...
- Android Studio系列教程五--Gradle命令详解与导入第三方包
Android Studio系列教程五--Gradle命令详解与导入第三方包 2015 年 01 月 05 日 DevTools 本文为个人原创,欢迎转载,但请务必在明显位置注明出处!http://s ...
- CentOS7/RHEL7安装Redis步骤详解
CentOS7/RHEL7安装Redis步骤详解 CentOS7/RHEL7安装Redis还是头一次测试安装了,因为centos7升级之后与centos6有比较大的区别了,下面我们就一起来看看Cent ...
- Redis协议详解
smark Beetle可靠.高性能的.Net Socket Tcp通讯组件 支持flash amf3,protobuf,Silverlight,windows phone Redis协议详解 由于前 ...
- Redis学习——详解Redis配置文件(三)
一.Redis脚本简介 在我们介绍Redis的配置文件之前,我们先来说一下Redis安装完成后生成的几个可执行文件: redis-server .redis-cli .redis-benchmark ...
- Redis:默认配置文件redis.conf详解
转: Redis:默认配置文件redis.conf详解 # Redis配置文件样例 # Note on units: when memory size is needed, it is possibl ...
随机推荐
- Tensorflow之快速加载MNIST数据集
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf def myprint(v): p ...
- php -- PDO预处理
可以使用多种方式实现预处理:指的是在绑定数据进行执行的时候,可以有多种方式. 预处理语句中为变量 使用数组指定预处理变量 1.准备预处理语句(发送给服务器,让服务器准备预处理语句) PDOStatem ...
- 转载:pyqt的signal和solit
转自:http://blog.csdn.net/hlqyq/article/details/6713828 import sysfrom PyQt5.QtCore import pyqtSignal, ...
- 解决myeclipse启动慢的问题
去掉拼写检查:windows->preferences->General->Editors->Text Editors->Spelling 将"Enable s ...
- Loadrunner如何遍历一个页面中的url并进行访问?
最近在网上到一个关于loadrunner遍历一个页面中的url并进行访问的脚本,就把它用我们自己的项目实践了一下,发现有一点不完善. 原始版本: Action(){char temp[64];int ...
- HDU 1058 Humble Numbers (动规+寻找丑数问题)
Humble Numbers Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) T ...
- SmartGit Mac、Liunx、Windows过期后破解方法
根据自己的操作系统,进入相应的文件夹 ,可能还有一个版本号的文件夹,再进入 Windows: %APPDATA%\syntevo\SmartGit\ OS X: ~/Library/Preferenc ...
- iOS:友盟SDK第三方登录 分享及友盟统计的使用
本文转载至 http://www.it165.net/pro/html/201503/37101.html Tag标签:第三方 01.#import "UMSocial.h" ...
- linux的/etc/hosts的作用
转自:http://blog.chinaunix.net/uid-28559065-id-4145820.html linux /etc/hosts文件作用 分类: LINUX linux /e ...
- Linux下查看nginx的安装路径
输入:nginx -V 输出:configure arguments: --prefix=/usr/local/nginx