szktor/hyperf3-mqtt-client

v3.0.0 2025-07-25 03:31 UTC

This package is not auto-updated.

Last update: 2025-07-26 01:42:28 UTC


README

  • 注意php >= 8.1
$ composer require szktor/hyperf3-mqtt-client

配置项

配置项类型默认值备注
hoststring'localhost'MQTT地址
portint1883MQTT端口
user_namestring用户名
passwordstring密码
keep_aliveint60保活时间
protocolstring3.1.1mqtt协议版本
repositorystring\PhpMqtt\Client\Repositories\MemoryRepository::class仓储对象,默认内存
clean_sessionbooletrue会话清除
poolobject{}连接池配置
return [
    'default' => [
        'host'          => env('MQTT_HOST', 'localhost'),
        'port'          => (int)env('MQTT_PORT', 1883),
        'client_id'     => env('MQTT_CLIENT_ID', md5('test-' . microtime())),
        'user_name'     => env('MQTT_USERNAME', ''),
        'password'      => env('MQTT_PASSWORD', ''),
        'keep_alive'    => (int)env('MQTT_KEEP_ALIVE', 20),
        'protocol'      => \PhpMqtt\Client\MqttClient::MQTT_3_1_1,
        'repository'    => \PhpMqtt\Client\Repositories\MemoryRepository::class,
        'clean_session' => true,
        'pool'          => [
            'min_connections' => 1,
            'max_connections' => 10,
            'connect_timeout' => 10.0,
            'waitTimeout'     => 3.0,
            'heartbeat'       => -1,
            'maxIdleTime'     => (int)env('MQTT_KEEP_ALIVE', 20) * 1.5,
        ]
    ]
];

publish完整配置文件使用命令

$ php bin/hyperf.php vendor:publish szktor/hyperf3-mqtt-client

使用

szktor/hyperf3-mqtt-client实现了php-mqtt/client代理和连接池,用户可以直接通过依赖注入\Hyperf\Mqttclient\Mqtt来使用mqtt客户端,实际获取的是一个\PhpMqtt\Client\MqttClient的一个代理对象.

<?php
use Hyperf\Context\ApplicationContext;
$container = ApplicationContext::getContainer();
$mqtt = $container->get(Hyperf\MqttClient\Mqtt::class);
$mqtt->publish('helloWorld', 'test');