天天看點

使用消息服務(MNS)訂閱阿裡雲物聯網平台裝置消息PHP示例參考

作者:俏巴

概述

物聯網平台服務端訂閱支援将裝置消息發送至消息服務(MNS),雲端應用通過監聽MNS隊列,擷取裝置消息。本文主要示範使用最新版MNS PHP SDK消費訂閱到MNS Queue中的消息。

操作步驟

1、服務端訂閱配置

參考連結

,連結中介紹了服務端MNS訂閱的配置及使用Java SDK擷取Queue中消息的方法。

2、

MNS PHP SDK

安裝

composer.json
{
  "require": {
     "aliyun/aliyun-mns-php-sdk": ">=1.0.0"
  }
}
           
Install
composer install           

3、Code Sample

<?php

require_once 'vendor/autoload.php';

use AliyunMNS\Client;
use AliyunMNS\Exception\MnsException;

class CreateQueueAndSendMessage
{
    private $accessId;
    private $accessKey;
    private $endPoint;
    private $client;
    private $queueName;

    public function __construct($accessId, $accessKey, $endPoint, $queueName)
    {
        $this->accessId = $accessId;
        $this->accessKey = $accessKey;
        $this->endPoint = $endPoint;
        $this->queueName = $queueName;
    }

    public function run()
    {
        $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);

        $queue = $this->client->getQueueRef($this->queueName);

        $receiptHandle = NULL;
        try
        {
            // when receiving messages, it's always a good practice to set the waitSeconds to be 30.
            // it means to send one http-long-polling request which lasts 30 seconds at most.
            $res = $queue->receiveMessage(30);
            echo "ReceiveMessage Succeed! \n";
            
            // json 對象轉數組
            $aTest = json_decode($res->getMessageBody(), true);
            // 擷取  payLoad 的值
            $payLoad = $aTest["payload"];
            
            // base64 解碼
            echo base64_decode($payLoad);
            $receiptHandle = $res->getReceiptHandle();
        }
        catch (MnsException $e)
        {
            echo "ReceiveMessage Failed: " . $e;
            return;
        }
        
        // 4. delete message
        try
        {
            $res = $queue->deleteMessage($receiptHandle);
            echo "<br/> DeleteMessage Succeed! \n";
        }
        catch (MnsException $e)
        {
            echo "DeleteMessage Failed: " . $e;
            return;
        }
    }
}

// ak,sk資訊擷取可以參考連結:https://yq.aliyun.com/articles/693979?spm=a2c4e.11155435.0.0.5ad926a2HiTVqH
// endPoint、queueName擷取到MNS管理控制台:https://mns.console.aliyun.com/
$accessId = "********";
$accessKey = "********";
$endPoint = "http://********.mns.cn-shanghai.aliyuncs.com/";
$queueName = "aliyun-iot-********";

if (empty($accessId) || empty($accessKey) || empty($endPoint))
{
    echo "Must Provide AccessId/AccessKey/EndPoint to Run the Example. \n";
    return;
}

$instance = new CreateQueueAndSendMessage($accessId, $accessKey, $endPoint,$queueName);
$instance->run();

?>
           

4、項目結構

使用消息服務(MNS)訂閱阿裡雲物聯網平台裝置消息PHP示例參考

5、運作結果

使用消息服務(MNS)訂閱阿裡雲物聯網平台裝置消息PHP示例參考