PHP(tp5.0)阿里云物联网 Stomp 服务端订阅 使用

PHP(tp5.0)SDK接入阿里云物联网平台 接收服务端订阅消息的示例

通过阅读阿里云物联网平台的产品文档中了解到,使用AMQP服务端与Stomp PHP库,来接收服务端订阅消息。前提准备如下(需电脑安装JDK环境)

一、ActiveMQ安装部署

  1. 下载
    到官网下载最新版本,有windows版本和linux版本的,在此以windows为例
    链接: http://activemq.apache.org/download.html.

  2. 部署
    将压缩包解压到所需要的目录,解压后的目录如下图
    在这里插入图片描述
    进入bin目录后,有win32位和win64两个文件夹,分别对应win32位和win64位操作系统的启动脚本
    在这里插入图片描述

我的环境是64位,进入win64目录后,启动activemq.bat,启动成功自动关闭
在这里插入图片描述
ActiveMQ默认启动到8161端口,启动完后在浏览器地址输入:http://localhost:8161/admin
要求输入用户名+密码,默认用户名+密码为:admin。
用户名+密码可在conf/user.properties中修改。
输入用户名+密码即可进入ActiveMQ控制台界面了,如下图
在这里插入图片描述

二、Stomp安装部署

  1. 下载
    链接: https://www.php.net/
    要与php版本一致,我的是php 5.6.27-nts,将压缩包解压到所需要的目录,解压后的目录如下图
    在这里插入图片描述

php_stomp.dll 文件粘贴到PHP所需要版本的ext文件中,
在这里插入图片描述

在php.ini中添加extension=php_stomp.dll
在这里插入图片描述
重启phpstudy,进入phpinfo.php查看是否有stomp,如有则成功,如下图
在这里插入图片描述

composer安装:

Composer require stomp-php/stomp-php

此命令结束后,会在C:\Users\**路径下生成一个stomp-php文件,将此文件放入项目中vendor文件下,如下图(此步至关重要 必须实现)
在这里插入图片描述

Stomp扩展安装成功,配置ActiveMQ安装目录下的config/actovemp.xml

<transportConnectors>
	<transportConnector name="openwire" uri="tcp://0.0.0.0:8161"/>
	<transportConnector name="stomp" uri="stomp://0.0.0.0:61613"/>
</transportConnectors>

三、使用Stomp

安装后,使用阿里云提供的示例代码,新建控制器Amqpgetmsg.php代码如下

<?php
namespace app\baapi\controller;

use Stomp\Client;
use Stomp\Network\Observer\Exception\HeartbeatException;
use Stomp\Network\Observer\ServerAliveObserver;
use Stomp\StatefulStomp;

class Amqpgetmsg {

    public function start_consume() {
        //参数说明,请参见AMQP客户端接入说明文档。
        $accessKey = '${YourAccessKeyId}';
        $accessSecret = '${YourAccessKeySecret}';
        $consumerGroupId = "${YourConsumerGroupId}";
        //iotInstanceId:购买的实例请填写实例ID,公共实例请填空字符串""。
        $iotInstanceId = "";
        $timeStamp = round(microtime(true) * 1000);
        //签名方法:支持hmacmd5,hmacsha1和hmacsha256。
        $signMethod = "hmacsha1";
        // 此处clientID 为自定义
        $clientId = "${YourClientId}";
        //userName组装方法,请参见AMQP客户端接入说明文档。
        //若使用二进制传输,则userName需要添加encode=base64参数,服务端会将消息体base64编码后再推送。具体添加方法请参见下一章节“二进制消息体说明”。
        $userName = $clientId . "|authMode=aksign"
            . ",signMethod=" . $signMethod
            . ",timestamp=" . $timeStamp
            . ",authId=" . $accessKey
            . ",iotInstanceId=" . $iotInstanceId
            . ",consumerGroupId=" . $consumerGroupId
            . "|";
        $signContent = "authId=" . $accessKey . "&timestamp=" . $timeStamp;
        //计算签名,password组装方法,请参见AMQP客户端接入说明文档。
        $password = base64_encode(hash_hmac("sha1", $signContent, $accessSecret, $raw_output = TRUE));
        //接入域名,请参见AMQP客户端接入说明文档。下方 123456 替换为你的阿里云账号id, cn-shanghai 替换为你的地区代码  若是PHP开发,端口号是  61614
        $client = new Client('ssl://123456.iot-amqp.cn-shanghai.aliyuncs.com:61614');
        $sslContext = ['ssl' => ['verify_peer' => true, 'verify_peer_name' => false]];
        $client->getConnection()->setContext($sslContext);

        //服务端心跳监听。
        $observer = new ServerAliveObserver();
        $client->getConnection()->getObservers()->addObserver($observer);
        //心跳设置,需要云端每10s发送一次心跳包。
        $client->setHeartbeat(0, 10000);
        $client->setLogin($userName, $password);
        try {
            $client->connect();
        } catch (StompException $e) {
            echo "failed to connect to server, msg:" . $e->getMessage(), PHP_EOL;
        }
        //无异常时继续执行。
        $stomp = new StatefulStomp($client);
        $stomp->subscribe('/topic/#');
        return $stomp;
    }

    public function index() {
        $stomp = $this->start_consume();
        while (true) {
            if ($stomp == null || !$stomp->getClient()->isConnected()) {
                echo "connection not exists, will reconnect after 10s.", PHP_EOL;
                sleep(10);
                $stomp = $this->start_consume();
            }

            try {
                //处理消息业务逻辑。
                echo $stomp->read();
            } catch (HeartbeatException $e) {
                echo 'The server failed to send us heartbeats within the defined interval.', PHP_EOL;
                $stomp->getClient()->disconnect();
            } catch (Exception $e) {
                echo 'process message occurs error ' . $e->getMessage(), PHP_EOL;
            }
        }
    }
};

以api模块为例,新建command文件,新建Stomp.php代码如下

<?php
namespace app\baapi\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Request;

class Stomp extends Command {
    protected function configure() {
        // 进程名,下文命令行中会体现
        $this->setName('stompsub')->setDescription('订阅打Stomp');
    }

    protected function execute(Input $input, Output $output) {
        $request = new Request();
        // 被执行代码所在模块
        $request->module("baapi");
        // 控制器和方法
        $output->writeln(controller('baapi/Amqpgetmsg')->index());
    }
}

在Appication目录下的command.php文件中新增刚新建的文件

return [
    'app\admin\command\Stomp',
];

至此,PHP端代码部分结束,切换到命令行工具,定位到我们的项目根目录(think文件所在的目录),执行

php think stompsub

其中,stompsub是Stomp.php的进程名,运行结果如下图
在这里插入图片描述
至此,Stomp已经订阅并接收到了设备上报的消息,可以查看物联网平台日志,如下图
在这里插入图片描述
【注】第一次写这种说明,有不全面的地方,还请各位大佬指点一二

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值