環境準備 首先需要安裝 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();
}
}
複製程式碼
閱讀原文請訪問