环境准备 首先需要安装 swoole 可以使用 pecl 进行安装 ,如 pecl install swool, 注意加上版本号

或者使用构建好的 docker 镜像,这里使用构建好的 zacksleo/php:7.1-alpine-fpm-swoole 镜像

使用 compose 安装依赖库

composer require jesusslim/mqttclient

<?php
 
namespace console\controllers;
 
use yii;
use console\components\mqtt\Logger;
use console\components\mqtt\Store;
use yii\console\Controller;
use mqttclient\src\swoole\MqttClient;
use mqttclient\src\subscribe\Topic;
 
class MqttController extends Controller
{
    public function actionClient()
    {
        $r = new MqttClient(getenv('TOKEN_MQTT_HOST'), getenv('TOKEN_MQTT_PORT'), 'push-server-client');
        $r->setAuth(getenv('TOKEN_MQTT_USERNAME'), getenv('TOKEN_MQTT_PASSWORD'));
        $r->setKeepAlive(60);
        $r->setLogger(new Logger());
        $r->setStore(new Store());
        $r->setTopics(
            [
                //消息回执
                new Topic('user-auth/create', function (MqttClient $client, $msg) {
                    //$msg 为获取到的消息体
                }),
                //消息打开
                new Topic('user-auth/delete', function (MqttClient $client, $msg) {
                   //$msg 为获取到的消息体
                })
            ]
        );
        $r->connect();
    }
}
复制代码

阅读原文请访问

www.zxb8.cc/?p=515

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐