下载php_sdk
此文件在阿里云的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
<?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();
?>
最后还是需要将文件运行于后台循环请求,我就不会了...
网友评论