作者:俏巴
概述
物联网平台服务端订阅支持将设备消息发送至消息服务(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、项目结构
5、运行结果
参考链接
MNS PHP SDK