用beanstalk做延时队列
beanstalk安装
docker run -d -p 11300:11300 schickling/beanstalkd
生产者
php
-
下载 pda/pheanstalk 包
https://packagist.org/packages/pda/pheanstalk
根据自己php版本下载合适的版本 -
生产与消费
private $conn = null; private $delay = 0; private $topic; /** - DelayQueue constructor. - @param $topic string 队列名称 - @param $delay int 延迟时间 秒 */ function __construct($topic, $delay = 0) { //队列配置 $conf = config('delay_queue_conf'); try { //初始化链接 $this->conn = new Pheanstalk($conf['addr'], $conf['port']); //设置延时 $this->delay = $delay; //订单单签topic $this->topic = $topic; } catch (\Exception $e) {} } /** - 入队 - @param $data string 入队内容 - @return int 返回task—id 入队失败为0 */ public function put($data) { if ($this->conn == null) { return 0; } try { //选择topic 写入数据 return $this->conn->useTube($this->topic)->put($data, 1024, $this->delay, 60); } catch (\Exception $e) { return 0; } } /** - 出队 - @return string 队列内容 */ public function get() { try { //切换到topic $watcher = $this->watcher(); //消费 $job = $watcher->reserve(0); //消费完删除 $watcher->delete($job); //返回队列数据 return $job->getData(); } catch (Exception $e) { return ""; } } /** - 切换topic - @return Pheanstalk */ private function watcher() { return $this->conn->watch($this->topic); }