这篇文章主要介绍“Laravel如何整合Workerman命令行监听MQTT”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Larave...
这篇文章主要介绍“Laravel如何整合Workerman命令行监听MQTT”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Laravel如何整合Workerman命令行监听MQTT”文章能帮助大家解决问题。
安装Laravel,已安装可省略
现代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源加快安装速度。
安装workerman-mqtt
上面说了,用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.
新建artisan命令
既然是使用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等配合进行缓存或者使用消息队列等。
执行mqtt命令
和别的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”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注捷杰建站行业资讯频道,小编每天都会为大家更新不同的知识点。