MQ:Beanstalkd 队列复习(二)

一、下载第三方扩展pheanstalk

composer require pda/pheanstalk

 

二、公共文件conn.php

<?php
/**
 * 公共连接脚本
 */

include_once "vendor/autoload.php";
//$conn = \Pheanstalk\Pheanstalk::create('127.0.0.1',11300,10);

use Pheanstalk\Pheanstalk;

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

 

二、生产端代码producer.php

<?php
/**
 * beanstalkd生产者
 */

require "conn.php";

use Pheanstalk\Pheanstalk;

// Queue a Job
$pheanstalk
    ->useTube('testtube')
    ->put("job payload goes here\n");

$pheanstalk
    ->useTube('testtube')
    ->put(
        json_encode(['test' => 'data']),  // encode data in payload
        Pheanstalk::DEFAULT_PRIORITY,     // default priority
        30, // delay by 30s
        60  // beanstalk will retry job after 60s
    );

 

三、消费者代码consumer.php

<?php
/**
 * beanstalkd消费者
 */
require "conn.php";

// we want jobs from 'testtube' only.
$pheanstalk->watch('testtube');

// this hangs until a Job is produced.
$job = $pheanstalk->reserve();

try {
    $jobPayload = $job->getData();

    if(!empty($jobPayload)){
        print_r($jobPayload);
        $pheanstalk->delete($job);
    }
    // do work.

//    sleep(2);
//    // If it's going to take a long time, periodically
//    // tell beanstalk we're alive to stop it rescheduling the job.
//    $pheanstalk->touch($job);
//    sleep(2);
//
//    // eventually we're done, delete job.
//    $pheanstalk->delete($job);
}
catch(\Exception $e) {
    // handle exception.
    // and let some other worker retry.
    $pheanstalk->release($job);
}

 

四、gitee代码下载地址

https://gitee.com/eoo-tec/beanstalk-review

 

本博客地址: wukong1688

本文原文地址:https://www.cnblogs.com/wukong1688/p/13347747.html

转载请著名出处!谢谢~~

 

posted @ 2020-07-20 21:09  wukong1688  阅读(150)  评论(0编辑  收藏  举报