如何在tp6框架里 运行mqtt 发布和订阅 已经用mqtt/php-client做了一版,可以运行。但是容易断开连接,不知道什么参数没有配置对。
启动服务
win平台
php think mqttSub
Linux平台
sleep 10
app_dir="/www/wwwroot/hq.maotouying.cc"
pid=${app_dir}/runtime/mqttSub_pid.pid
su - www <<EOF
echo "start mqttSub...."
echo $app_dir
echo $pid
if [ -f "$pid" ]
then
if [ $(cat $pid) ]
then
kill -9 `cat ${app_dir}/runtime/mqttSub_pid.pid`
fi
fi
nohup /usr/bin/php ${app_dir}/think mqttSub > ${app_dir}/runtime/mqttSub`date +'%Y-%m-%d'`.log 2>&1 &
echo $! > ${app_dir}/runtime/mqttSub_pid.pid
echo "mqttSub started"
EOF
指令配置文件
return [
// 指令定义
'commands' => [
'mqttSub' => 'app\command\mqttSubscribe',
],
];
指令定义
mqttSubscribe.php
<?php
declare (strict_types = 1);
namespace app\command;
use app\admin\service\MqttSubService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class mqttSubscribe extends Command
{
protected function configure()
{
$this->setName('mqttsubscribe')
->setDescription('the mqttsubscribe command');
}
protected function execute(Input $input, Output $output)
{
$MqttSubService = new MqttSubService();
$output->writeln($MqttSubService->sub());
}
}
mqttSubService.php核心业务方法
public function sub()
{
ignore_user_abort(true);
set_time_limit(0);
date_default_timezone_set('PRC');
$this->mqtt = new \PhpMqtt\Client\MqttClient($this->host, $this->port, $this->client);
$connectionSettings = (new \PhpMqtt\Client\ConnectionSettings)
->setUsername($this->username)
->setPassword($this->password)
->setTlsClientCertificateKeyPassphrase(null);
$this->mqtt->connect($connectionSettings,true);
if (!$this->mqtt->isConnected()){
echo "mqtt链接失败";
}
$this->mqtt->subscribe($this->topics_name,function($topic,$message){
$this->message($topic,$message);
});
$this->mqtt->loop(true);
$this->mqtt->disconnect();
}
正在使用workerman/mqtt做第二版,目前测试可以。上线稳定运行后,回来上代码!!!
|