redis 能不能监听特定的key失效_php监听redis key失效触发回调事件
訂單超時、活動過期解決方案:php監聽redis key失效觸發回調事件
Redis 的 2.8.0 版本之后可用,鍵空間消息(Redis Keyspace Notifications),配合 2.0.0 版本之后的 SUBSCRIBE就能完成這個定時任務的操作了,定時的單位是秒。
1.我們先訂閱頻道名為 redisChat
2.現在,我們重新開啟個 redis 客戶端,然后在同一個頻道 redisChat 發布消息,訂閱者就能接收到消息。
接收到的消息如下:
3.Key過期事件的Redis配置
這里需要配置 notify-keyspace-events 的參數為 “Ex”。x 代表了過期事件。notify-keyspace-events “Ex” 保存配置后,重啟Redis服務,使配置生效。
PHP redis實現訂閱鍵空間通知
redis實例化類:
redis.class.php//遇到類別重復的報錯,所有叫Redis2
class Redis2
{
private $redis;
public function __construct($host = '127.0.0.1', $port = 6379)
{
$this->redis = new Redis();
$this->redis->connect($host, $port);
}
public function setex($key, $time, $val)
{
return $this->redis->setex($key, $time, $val);
}
public function set($key, $val)
{
return $this->redis->set($key, $val);
}
public function get($key)
{
return $this->redis->get($key);
}
public function expire($key = null, $time = 0)
{
return $this->redis->expire($key, $time);
}
public function psubscribe($patterns = array(), $callback)
{
$this->redis->psubscribe($patterns, $callback);
}
public function setOption()
{
$this->redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
}
}
過期事件的訂閱:
psubscribe.phprequire_once './Redis.class.php';
$redis = new \Redis2();
// 解決Redis客戶端訂閱時候超時情況
$redis->setOption();
$redis->psubscribe(array('__keyevent@0__:expired'), 'keyCallback');
// 回調函數,這里寫處理邏輯
function keyCallback($redis, $pattern, $chan, $msg)
{
echo "Pattern: $pattern\n";
echo "Channel: $chan\n";
echo "Payl
oad: $msg\n\n";
//keyCallback為訂閱事件后的回調函數,這里寫業務處理邏輯,
//比如前面提到的商品不支付自動撤單,這里就可以根據訂單id,來實現自動撤單
}
設置過期事件:
index.phprequire_once './Redis.class.php';
$redis = new \Redis2();
$order_id = 123;
$redis->setex('order_id',10,$order_id);
先用命令行模式執行 psubscribe.php
在瀏覽器訪問index.php
效果如下:
更多相關php知識,請訪問php教程!
總結
以上是生活随笔為你收集整理的redis 能不能监听特定的key失效_php监听redis key失效触发回调事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python自然场景文字识别_chine
- 下一篇: php接收get数组数据,来自HTTP的