美文网首页
获取阿里云mns队列消息并删除

获取阿里云mns队列消息并删除

作者: adtk | 来源:发表于2017-12-05 18:06 被阅读0次

下载php_sdk

http://docs-aliyun.cn-hangzhou.oss.aliyun-inc.com/assets/attach/32381/cn_zh/1496733042815/aliyun-mns-php-sdk-1.3.5.zip?spm=5176.doc32381.2.4.QFFtb1&file=aliyun-mns-php-sdk-1.3.5.zip

此文件在阿里云的php_sdk\Samples\Queue\CreateQueueAndSendMessage.php

获取accessId和accessKey (我用的RAM子用户)

https://ak-console.aliyun.com/?spm=5176.doc34414.2.4.JUpwRu#/accesskey

下图是queueName和endPoint

https://mns.console.aliyun.com/#/list/cn-shanghai

image.png
<?php
require_once('./php_sdk/mns-autoloader.php');

use AliyunMNS\Client;
use AliyunMNS\Requests\SendMessageRequest;
use AliyunMNS\Requests\CreateQueueRequest;
use AliyunMNS\Exception\MnsException;
class CreateQueueAndSendMessage{
    private $accessId;
    private $accessKey;
    private $endPoint;
    private $client;

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

    public function run() {
        $queueName = "";//这里是queueName

        $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);
       
        $queue = $this->client->getQueueRef($queueName);
      
        $receiptHandle = NULL;

        try{// 从队列获取消息,
            $res = $queue->receiveMessage(20);//长连接时间30s
            echo "获取消息成功!<br>";
            $receiptHandle = $res->getReceiptHandle();//消息临时句柄,用它删除消息
            $msg=json_decode($res->getMessageBody());
            echo base64_decode($msg->payload);

            // $msg为消息,有topic等,自己打印
            // $msg->payload为上下线记录或者设备上传数据
            //上下线记录:
            // {"lastTime":"2017-11-17 17:51:38.375","clientIp":"211.161.37.5","time":"2017-11-17 17:51:38.389","productKey":"bZQ6DszUOTV","deviceName":"test2","status":"online"}

        }catch (MnsException $e){
            echo "获取消息失败:<br> " . $e;
            return;
        }
        // 4. 删除message
        try{
            $res = $queue->deleteMessage($receiptHandle);
            echo "删除消息成功! \n";
        }catch (MnsException $e){
            echo "删除消息失败: " . $e;
            return;
        }
    }
}
//这里赋值 
$accessId = "";
$accessKey = "";
$endPoint = "";

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);
$instance->run();

?>

最后还是需要将文件运行于后台循环请求,我就不会了...

相关文章

网友评论

      本文标题:获取阿里云mns队列消息并删除

      本文链接:https://www.haomeiwen.com/subject/qrswbxtx.html