codemix /yiiredis
熟悉的Yii风格访问Redis
1.0.0
2013-11-01 11:00 UTC
This package is auto-updated.
Last update: 2024-08-24 04:15:16 UTC
README
提供面向对象的Redis访问,以熟悉的Yii风格。当你在Redis实体(列表、集合、有序集合、散列)中添加或删除项目时,更改会立即推送到服务器,这在您的应用程序需要跨多个请求提供信息时很有用。
此包依赖于https://github.com/nicolasff/phpredis PHP扩展,请在继续之前确保已安装。
使用
配置Redis连接
将以下内容添加到您的应用程序配置中
"components" => array( "redis" => array( "class" => "packages.redis.ARedisConnection", "hostname" => "localhost", "port" => 6379, "database" => 1, "prefix" => "Yii.redis." ), ... ),
存储和检索简单键值
要存储一个简单值到一个键并读取它
Yii::app()->redis->getClient()->set("myKey", "Your Value"); echo Yii::app()->redis->getClient()->get("myKey"); // outputs "Your Value" Yii::app()->redis->getClient()->del("myKey"); // deletes the key
使用列表
Redis列表是按添加项目的顺序保存的简单值列表
$list = new ARedisList("aNameForYourListGoesHere"); $list->add("cats"); $list->add("dogs"); $list->add("fish"); foreach($list as $i => $val) { echo $val."<br />"; } $list->clear(); // delete the list
使用集合
Redis集合是无序的非重复值列表
$set = new ARedisSet("aNameForYourSet"); $set->add(1); $set->add(2); $set->add(3); echo $set->count; // outputs 3 $set->add(3); echo $set->count; // still 3, cannot add the same value more than once foreach($set as $val) { echo $val."<br />"; }
使用有序集合
Redis有序集合是非重复值的列表,每个值都与一个分数相关联,该分数影响结果的顺序
$sortedSet = new ARedisSortedSet("aNameForYourSortedSet"); $sortedSet->add("myValue", 0.4); $sortedSet->add("myOtherValue", 0.8); $sortedSet->add("myOtherOtherValue", 0.9); foreach($sortedSet as $key => $score) { echo $key.": ".$score."<br />"; }
使用散列
Redis散列是字符串字段和字符串值之间的映射,因此它们是表示对象的完美数据类型(例如:具有姓名、姓氏、年龄等字段的用户)。
$hash = new ARedisHash("myHashNameHere"); $hash->whatever = "someValue"; $hash->greeting = "hello world"; echo $hash->count; // outputs 2
使用Pub/Sub
Redis允许我们订阅频道并向它们发布消息。
$channel = new ARedisChannel("myChan"); $channel->onReceiveMessage = function($redis, $channel, $message) { echo "Message Received: ".$message."\n"; } $channel->publish("hello world"); // sends a messsage to the channel $channel->subscribe(); // subscribes to the channel and listens to messages, blocks the process
使用Redis作为计数器
我们经常需要存储特定数据库表或行的计数器,使用YiiRedis这既快又简单。
$counter = new ARedisCounter("totalPageViews"); $counter->increment(); echo $counter->getValue();
使用Redis作为互斥锁
互斥锁有助于确保一次只有一个客户端可以访问特定的资源。
$mutex = new ARedisMutex("someOperation"); $mutex->block(); // blocks execution until the resource becomes available // do something $mutex->unlock(); // release the lock
使用Redis进行缓存
由于速度可比且数据持久,Redis是memcached的良好缓存替代品。
在您的应用程序配置中
"components" => array( "cache" => array( "class" => "packages.redis.ARedisCache" ), ... ),
将Redis用作Active Record的后端
可以使用ARedisRecord将Active Record类似结构存储在Redis中。
注意:这是实验性功能,可能随时更改
$record = ARedisRecord::model()->findByPk(1); // loads a record with a unique id of 1 $record->name = "a test name"; // sets the name attribute on the record $record->somethingElse = "some other value"; $record->save(); // saves the record to redis $record->delete(); // deletes the record from redis