您好,登錄后才能下訂單哦!
這篇文章主要介紹“Laravel如何整合Workerman命令行監聽MQTT”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Laravel如何整合Workerman命令行監聽MQTT”文章能幫助大家解決問題。
現代PHP開發composer應該是必不可少的了,基本上大點的框架都會推薦使用composer,所以這里以composer來安裝Laravel,命令如下:
composer create-project --prefer-dist laravel/laravel workerman-mqtt ‘5.5.*’
Laravel指定版本為5.5.x,這是目前(2019.08)的唯一LTS版本,考慮到企業項目的穩定及安全,還是選擇LTS。項目名稱為workerman-mqtt,專門用這個來測試MQTT。
如果composer太慢,可以考慮使用阿里云等國內composer源加快安裝速度。
上面說了,用composer安裝workerman-mqtt很簡單,只需要一行命令:
? cd workerman-mqtt
? composer require workerman/mqtt
Using version ^1.0 for workerman/mqtt
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
- Installing workerman/workerman (v3.5.20): Loading from cache
- Installing workerman/mqtt (v1.0): Loading from cache
workerman/workerman suggests installing ext-event (For better performance. )
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating optimized autoload files
Carbon 1 is deprecated, see how to migrate to Carbon 2.
https://carbon.nesbot.com/docs/#api-carbon-2
You can run './vendor/bin/upgrade-carbon' to get help in updating carbon and other frameworks and libraries that depend on it.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Package manifest generated successfully.
既然是使用Laravel配合workerman監聽MQTT,那artisan自然是不二的選擇了,能使用Laravel的組件,還能使用artisan命令管理監聽進程。創建相關命令文件:
? php artisan make:command mqtt
Console command created successfully.
然后編輯生成的workerman-mqtt/app/Console/Commands/mqtt.php文件,將文件改成如下內容:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Workerman\Worker;
class mqtt extends Command
{
protected $signature = 'mqtt {action}';
protected $description = 'PHP Server MQTT Client';
protected $client_id = 'php-server';
public function __construct()
{
parent::__construct();
}
public function handle()
{
global $argv;
$arg = $this->argument('action');
$argv [1] = $arg;
$worker = new Worker();
$worker->count = 1;
$worker->onWorkerStart = function () {
$mqtt = new \Workerman\Mqtt\Client("mqtt://" . env('MQTT_HOST') . ":" . env('MQTT_PORT'), array(
// 'ssl' => array(
// 'local_cert' => base_path() . '/path/mqtt/client.crt',
// 'local_pk' => base_path() . '/path/mqtt/client.key',
// 'cafile' => base_path() . '/path/mqtt/ca.crt',
// 'verify_peer' => false,
// 'allow_self_signed' => true,
// ),
// $mqtt->transport = 'ssl';
'username' => env('MQTT_USER'),
'password' => env('MQTT_PASSWORD'),
'debug' => env('MQTT_DEBUG'),
'client_id' => $this->client_id . mt_rand(0, 999),
'will' => [
'topic' => 'status/' . $this->client_id,
'content' => 0,
'qos' => 2,
'retain' => true,
]
));
$mqtt->onConnect = function ($mqtt) {
$mqtt->subscribe('/iot/#');
};
$mqtt->onMessage = function ($topic, $data, $mqtt) {
var_dump($topic);
var_dump($data);
//TODO 業務代碼
//publish消息到topic
$mqtt->publish('test', 'hello workerman mqtt');
};
$mqtt->connect();
};
Worker::runAll();
}
}
然后到項目根目錄下面的.env文件添加下面幾項:
MQTT_HOST=mqtt-broker.test
MQTT_PORT=1883
MQTT_USER=username
MQTT_PASSWORD=password
MQTT_DEBUG=true
其中,onConnect里面的subscribe后面是需要監聽的topic,當收到新消息的時候,onMessage里面的topic是消息的topic,data就是具體的消息信息了,有了這兩個,我們可以在onMessage里面寫我們的業務邏輯,當然也可以引入Laravel框架本身的一些組件,比如數據庫、日志等,也可以與別的服務比如說Redis、消息隊列MQ等配合進行緩存或者使用消息隊列等。
和別的artisan命令差不多,直接命令行運行就好了:
? php artisan mqtt start
Workerman[artisan] start in DEBUG mode
------------------------------------- WORKERMAN --------------------------------------
Workerman version:3.5.20 PHP version:7.1.30
-------------------------------------- WORKERS ---------------------------------------
proto user worker listen processes status
tcp zoco none none 1 [OK]
--------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.
-> Try to connect to mqtt://mqtt-broker.test:1883
-- Tcp connection established
-> Send CONNECT package client_id:php-server-superuser-subscribe95 username:username password:password clean_session:1 protocol_name:MQTT protocol_level:4
<- Recv CONNACK package, MQTT connect success
-> Send SUBSCRIBE package, topic:/iot/# message_id:1
<- Recv SUBACK package, message_id:1
注意別忘了后面的start,這是workerman本身需要的啟動參數。
因為workerman設定是常駐內存,正常情況下是在持續在監聽的,即使程序有bug被終止,workerman也會自動新建一個進程進行處理。
如果生產環境需要長期監聽處理MQTT數據,建議使用systemctl等命令來管理。
雖然到上面為止已經可以作為客戶端在服務端監聽MQTT的消息,但是這里有個不足之處就是,我到目前沒找到辦法單獨調用這個庫在處理實際業務邏輯的時候publish消息到指定的topic。
還有一點是,使用這個庫,不能同時運行兩個使用了這個庫的artisan命令,會有如下提示:
? php artisan mqtt start
Workerman[artisan] start in DEBUG mode
Workerman[artisan] already running
這個問題搜遍了全網也沒發現有解決的辦法。雖然可以通過Timer類添加定時功能通過另類辦法解決,但是在需要效率的情況下,這并不是最優解,如果有別的方案,建議還是不要選擇PHP作為服務端來處理MQTT相關業務。
關于“Laravel如何整合Workerman命令行監聽MQTT”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。