基于simps mqtt的mqtt客户端封装

0.1.5 2024-05-27 03:48 UTC

This package is auto-updated.

Last update: 2024-09-27 04:25:58 UTC


README

Coroutine MQTT 客户端与 Hyperf 框架集成

此库使用 simps/mqtt,请参阅 https://mqtt.simps.io/#/en/ 了解兼容性

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

此库仅支持 MQTT 5

安装

composer require nashgao/mqtt

发布配置

php bin/hyperf.php vendor:publish nashgao/mqtt

设计目的

共享订阅 是 MQTT 5 中引入的新功能。它允许多个订阅者订阅同一主题,但在同一时间只有其中一个订阅者接收消息

                                                   [subscriber1] got msg1
             msg1, msg2, msg3                    /
[publisher]  ---------------->  "$share/g/topic"  -- [subscriber2] got msg2
                                                 \
                                                   [subscriber3] got msg3
   

图表 所示,订阅者 1、2、3 属于同一组 g,在 topic 下,其中 $share 是主题的常量前缀。

当消息 1、2、3 逐步发布时,组内的订阅者中只有一个会收到消息,而不是所有订阅者(《队列主题》是共享订阅的特殊情况,其中组 g 变为常量字符串 $queue)。

为了使订阅更简单,此库被设计和集成到 Hyperf 框架中。该库使用 simps/mqtt,这是第一个支持 MQTT 5 的 PHP mqtt 库,用于基本的 mqtt 代理交互。

用法

  • 订阅

    • 自动订阅
      • 对于在您的 config/autoload/mqtt.php 下定义的每个主题,如果 auto_subscribe 被设置为 true,则在 Hyperf 服务器启动时将自动订阅该主题。
      • 如果启用 queue topic,则将短路共享主题选项
      • 启用 enable_multi_sub 选项作为 true,则将创建 multi_sub 个客户端来订阅相应主题
      • 选项 group_name 代表在“设计目的”部分提到的 g 选项
    • 手动订阅(在这些情况下,需要手动处理共享订阅)
      • 分发 Nashgao\MQTT\Event\SubscribeEvent 事件
        use Hyperf\Context\ApplicationContext;
        use Nashgao\MQTT\Config\TopicConfig;
        use Nashgao\MQTT\Event\SubscribeEvent;
        use Psr\EventDispatcher\EventDispatcherInterface;  
        
        $event = new SubscribeEvent(topicConfigs: [
            new TopicConfig([
               'topic' => 'topic/test',
               'qos' => 2
            ])
        ]);
        $dispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class);
        $dispatcher->dispatch($event);
      • 直接调用 Nashgao\MQTT\Client
        use Nashgao\MQTT\Client;
        
        $client = make(Client::class);
        $client->subscribe([
            'topic/test' => [
                'qos' => 2
            ]
        ]);  
  • 发布

    • 分发 Nashgao\MQTT\Event\PublishEvent
      use Hyperf\Event\EventDispatcher;
      use Hyperf\Context\ApplicationContext;
      use Nashgao\MQTT\Event\PublishEvent;
      use Psr\EventDispatcher\EventDispatcherInterface;
      
      $dispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class);
      $dispatcher->dispatch(new PublishEvent('topic/test', 'hi mqtt', 2)); 
    • 直接调用 Nashgao\MQTT\Client
    use Nashgao\MQTT\Client;
    
    $client = make(Client::class);
    $client->publish('topic/test', 'hi_mqtt', 2);