您的位置 首页 技术

php监听redis key失效触发回调事件

订单超时、活动过期解决方案:php监听redis key失效触发回调事件 Redis 的 2.8.0 版本之后可用,键空间消息(Redis Keyspace Notificatio…

订单超时、活动过期解决方案:php监听redis key失效触发回调事件

Redis 的 2.8.0 版本之后可用,键空间消息(Redis Keyspace Notifications),配合 2.0.0 版本之后的 SUBSCRIBE 就能完成这个定时任务的操作了,定时的单位是秒。

1.我们先订阅频道名为 redisChat

d97c70dbeb0ecf31bafa70bde2f629e.png

2.现在,我们重新开启个 redis 客户端,然后在同一个频道 redisChat 发布消息,订阅者就能接收到消息。

95f96008cc31b461473adf59181e0c2.png

接收到的消息如下:

994a7a4938bf37b8f59224278e90a83.png

3.Key过期事件的Redis配置

这里需要配置 notify-keyspace-events 的参数为 “Ex”。x 代表了过期事件。notify-keyspace-events “Ex” 保存配置后,重启Redis服务,使配置生效。

PHP redis实现订阅键空间通知

redis实例化类:

redis.class.php

//遇到类别重复的报错,所有叫Redis2class 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.php

require_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.php

require_once './Redis.class.php';$redis = new \Redis2();$order_id = 123;$redis->setex('order_id',10,$order_id);

先用命令行模式执行 psubscribe.php

在浏览器访问 index.php

效果如下:

c4802719d7cd03be48f80e3f31d27f8.png

更多相关php知识,请访问php教程!

以上就是php监听redis key失效触发回调事件的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/32208.html

为您推荐

返回顶部