Thinkphp对接RocketMQ 阿里云

2020-12-10  本文已影响0人  wyc0859

阿里云的RocketMQ多抗压就不描述了
阿里云RocketMQ有php的SDK包,直接拿来用有些坑,填填就好

文档:https://help.aliyun.com/document_detail/141783.html?spm=a2c4g.11186623.6.640.545fb6deL1n0Ix
SDK:https://github.com/aliyunmq/mq-http-php-sdk

1、开通RocketMQ并创建实例
2、创建AccessKey
3、SDK压缩包解压后,将MQ文件夹放入extend目录
4、安装Guzzle:composer require guzzlehttp/guzzle
5、执行订阅和发布

任务发布成功后,阿里云控制台能看见消息轨迹,及是否被消费。
消费 从代码来看就是一个while死循环,在linux系统下,应该是会被封杀的

订阅和发布

进行发布
1、新建一个发布类

namespace app\controller;
use MQ\Model\TopicMessage;
use MQ\MQClient;

class Sample{
    private $client;
    private $producer;
    public function __construct($accessId, $accessKey, $endPoint)    {
        $topic = "topic";// 所属的Topic。
        $groupId = "GID_1";// 您在控制台创建的Group ID(Consumer ID)。
        $instanceId = "MQ_INST_152"; // Topic所属实例ID,默认实例为空NULL。
        $this->client = new MQClient( $endPoint,$accessId, $accessKey);
        $this->producer = $this->client->getProducer($instanceId, $topic);
    }
    public function run(){
        try {
            $publishMessage = new TopicMessage(
                "xxxxxxxx"// 消息内容
            );            
            $publishMessage->putProperty("pro", 3);// 设置属性    
            $publishMessage->setMessageKey("qykey");        // 设置消息KEY
            $publishMessage->setStartDeliverTime(time() * 1000 + 10 * 1000);
            $result = $this->producer->publishMessage($publishMessage);
            print "Send mq message success. msgId is:" . $result->getMessageId() .
             ", bodyMD5 is:" .$result->getMessageBodyMD5() . "\n";
        } catch (\Exception $e) {
            print_r($e->getMessage() . "\n");
        }
    }
}

2、进行发布

namespace app\controller;
class Index{
    public function index()    { 
        $accessId = "xxx";
        $accessKey = "xxx";
        $endPoint = "http://1522.xxxx.com";
        if (empty($accessId) || empty($accessKey) || empty($endPoint)) {
            echo "Must Provide AccessId/AccessKey/EndPoint to Run the Example. \n";
            return;
        }
        $instance = new Sample($accessId, $accessKey, $endPoint);
        $instance->run();
    }

进行消费
1、新建一个消费类

namespace app\controller;
use MQ\Model\TopicMessage;
use MQ\MQClient;
class ConsumerTest{
    private $client;
    private $consumer;
    public function __construct($accessId, $accessKey, $endPoint)
    {
        $this->client = new MQClient($endPoint,$accessId, $accessKey);
        $topic = "topic";// 所属的Topic。
        $groupId = "GID";// 您在控制台创建的Group ID(Consumer ID)。
        $instanceId = "MQ_INS"; // Topic所属实例ID,默认实例为空NULL。
        $this->consumer = $this->client->getConsumer($instanceId, $topic, $groupId);
    }
    public function run()    {
        // 在当前线程循环消费消息,建议是多开个几个线程并发消费消息
        while (True) {
            try {
                // 长轮询消费消息
                // 长轮询表示如果topic没有消息则请求会在服务端挂住3s,3s内如果有消息可以消费则立即返回
                $messages = $this->consumer->consumeMessage(
                    3, // 一次最多消费3条(最多可设置为16条)
                    3 // 长轮询时间3秒(最多可设置为30秒)
                );
            } catch (\Exception $e) {
                if ($e instanceof MQ\Exception\MessageNotExistException) {
                    // 没有消息可以消费,接着轮询
                    printf("No message, contine long polling!RequestId:%s\n", $e->getRequestId());
                    continue;
                }
                sleep(3);
                continue;
            }
            // 处理业务逻辑
            $receiptHandles = array();
            foreach ($messages as $message) {
                $receiptHandles[] = $message->getReceiptHandle();
                printf("MessageID:%s TAG:%s BODY:%s \nPublishTime:%d, FirstConsumeTime:%d, \nConsumedTimes:%d, NextConsumeTime:%d,MessageKey:%s\n",
                    $message->getMessageId(), $message->getMessageTag(), $message->getMessageBody(),
                    $message->getPublishTime(), $message->getFirstConsumeTime(), $message->getConsumedTimes(), $message->getNextConsumeTime(),
                    $message->getMessageKey());
                print_r($message->getProperties());
                Log::error($message->getProperties());
            }
            // $message->getNextConsumeTime()前若不确认消息消费成功,则消息会重复消费
            // 消息句柄有时间戳,同一条消息每次消费拿到的都不一样
            print_r($receiptHandles);
            try {
                $this->consumer->ackMessage($receiptHandles);
            } catch (\Exception $e) {
                if ($e instanceof MQ\Exception\AckMessageException) {
                    // 某些消息的句柄可能超时了会导致确认不成功
                    printf("Ack Error, RequestId:%s\n", $e->getRequestId());
                    foreach ($e->getAckMessageErrorItems() as $errorItem) {
                        printf("\tReceiptHandle:%s, ErrorCode:%s, ErrorMsg:%s\n", $errorItem->getReceiptHandle(), $errorItem->getErrorCode(), $errorItem->getErrorCode());
                    }
                }
            }
        }
    }
}

2、进行消费

    public function show()    { 
        $accessId = "xxx";
        $accessKey = "xxx";
        $endPoint = "http://1522.xxxx.com";
        if (empty($accessId) || empty($accessKey) || empty($endPoint)) {
            echo "Must Provide AccessId/AccessKey/EndPoint to Run the Example. \n";
            return;
        }
        $instance = new ConsumerTest($accessId, $accessKey, $endPoint);
        $instance->run();
    } 
上一篇 下一篇

猜你喜欢

热点阅读