阿里云Rocket MQ PHP Http SDK发送消息示例Demo

Step By Step

1、SDK安装:composer.json

{
  "require": {
     "aliyunmq/mq-http-sdk": ">=1.0.1"
  }
}

2、install requires

composer install

3、认证参数获取

参考:阿里云Rocket MQ Java Http SDK发送消费消息示例Demo 参数获取部分

4、Send Code Sample

<?php
require "vendor/autoload.php";

use MQ\Model\TopicMessage;
use MQ\MQClient;

class ProducerTest
{
    private $client;
    private $producer;
    
    public function __construct()
    {
        $this->client = new MQClient(
            // 设置HTTP接入域名(此处以公共云生产环境为例)
            "http://1848217816617278.mqrest.cn-qingdao.aliyuncs.com",
            // AccessKey 阿里云身份验证,在阿里云服务器管理控制台创建
            "LTAIOZ**********",
            // SecretKey 阿里云身份验证,在阿里云服务器管理控制台创建
            "v7CjUJCMk7j9aK****************"
            );
        
        // 所属的 Topic
        $topic = "******";
        // Topic所属实例ID,默认实例为空NULL
        $instanceId = "MQ_INST_18482178********";
        
        $this->producer = $this->client->getProducer($instanceId, $topic);
    }
    
    public function run()
    {
        try
        {
            for ($i=1; $i<=4; $i++)
            {
                $publishMessage = new TopicMessage(
                    "this is test message"// 消息内容
                    );
                // 设置属性
                $publishMessage->putProperty("a", $i);
                // 设置消息KEY
                $publishMessage->setMessageKey("MessageKey");
                if ($i % 2 == 0) {
                    // 定时消息, 定时时间为10s后
                    $publishMessage->setStartDeliverTime(time() * 1000 + 10 * 1000);
                }
                $result = $this->producer->publishMessage($publishMessage);
                
                print "Send mq message success. msgId is:" . $result->getMessageId() . ", bodyMD5 is:" . $result->getMessageBodyMD5() . "\r\n";
                
                // 设置换行
                echo "<br>";
            }
        } catch (\Exception $e) {
            print_r($e->getMessage() . "\n");
        }
    }
}

$instance = new ProducerTest();
$instance->run();
?>

5、测试效果
阿里云Rocket MQ PHP Http SDK发送消息示例Demo

参考链接

PHP SDK 接入说明

上一篇:剑指offer题目详细版本(3)


下一篇:标准化:Normalization vs. 归一化:Standardization