延迟队列就是个带延迟功能的消息队列,相对于普通队列,它可以在指定时间消费掉消息。
延迟队列的应用场景:
1、新用户注册,10分钟后发送邮件或站内信。
2、用户下单后,30分钟未支付,订单自动作废。
我们通过redis的有序集合zset来实现简单的延迟队列,将消息数据序列化,作为zset的value,把消息处理时间作为score,每次通过zRangeByScore获取一条消息进行处理。
<?php
class DelayQueue
{
protected $prefix = 'delay_queue:';
protected $redis = null;
protected $key = '';
public function __construct($queue, $config = [])
{
$this->key = $this->prefix . $queue;
$this->redis = new Redis();
$this->redis->connect($config['host'], $config['port'], $config['timeout']);
$this->redis->auth($config['auth']);
}
public function delTask($value)
{
return $this->redis->zRem($this->key, $value);
}
public func