Loading

使用beanstalk作任务队列,延迟队列

使用beanstalk作任务队列,延迟队列

安装 各Linux发行版使用包管理工具, Ubuntu: sudo apt install beanstalkd 或下载源码编译
PHP客户端 composer require pda/pheanstalk 其他语言请看

//生产者
use Pheanstalk\Pheanstalk;

$pheanstalk = Pheanstalk::create('127.0.0.1');
$eventBase = new \EventBase();
$timer = new Event($eventBase, -1, Event::PERSIST | EVENT::TIMEOUT, function () use ($pheanstalk) {
    $now = time();
    $rand = mt_rand(1111, 9999);
    $delay = 1;
    $delaytime = $now + $delay;
    $data = ['to' => 'jj@qq.com', 'subject' => 'subject1', 'content' => 'content' . $rand, 'delaytime' => $delaytime];
    printf("%d\t%d\n", $now, $rand);
    $pheanstalk->useTube('email')->put(json_encode($data), 1024, $delay);
});
$timer->add(3);
$eventBase->loop();

这里使用Event timer作为示范, 实际使用从业务代码投递任务至队列

//消费者
use Pheanstalk\Pheanstalk;

$pheanstalk = Pheanstalk::create('127.0.0.1');

while (true) {
    $job = $pheanstalk->watch('email')->ignore('default')->reserve();
    //业务代码
    $buf = json_decode($job);
    mail_send($buf['to'], $buf['subject'], $buf['content']);
    $pheanstalk->delete($job);
}

posted @ 2021-01-21 09:10  chnyang  阅读(256)  评论(0编辑  收藏  举报