使用swoole作为MQTT客户端并接收实现即时消息推送

环境准备

首先需要安装swoole

可以使用pecl进行安装 ,如 pecl install swool, 注意加上版本号

或者使用构建好的docker镜像,这里使用构建好的 zacksleo/php:7.1-alpine-fpm-swoole 镜像

使用 compose 安装依赖库

composer require jesusslim/mqttclient

编写业务逻辑代码


<?php

namespace console\controllers;

use yii;
use console\components\mqtt\Logger;
use console\components\mqtt\Store;
use yii\console\Controller;
use mqttclient\src\swoole\MqttClient;
use mqttclient\src\subscribe\Topic;

class MqttController extends Controller
{
    public function actionClient()
    {
        $r = new MqttClient(getenv('TOKEN_MQTT_HOST'), getenv('TOKEN_MQTT_PORT'), 'push-server-client');
        $r->setAuth(getenv('TOKEN_MQTT_USERNAME'), getenv('TOKEN_MQTT_PASSWORD'));
        $r->setKeepAlive(60);
        $r->setLogger(new Logger());
        $r->setStore(new Store());
        $r->setTopics(
            [
                //消息回执
                new Topic('user-auth/create', function (MqttClient $client, $msg) {
                    //$msg 为获取到的消息体
                }),
                //消息打开
                new Topic('user-auth/delete', function (MqttClient $client, $msg) {
                   //$msg 为获取到的消息体
                })
            ]
        );
        $r->connect();
    }
}

执行命令

由于该客户端需要常驻内存,所以需要在 terminal 运行,如

./yii mqtt/client

进程保活

为了防止进程被杀死,获取因为异常退出,可以使用进程管理工具进行管理,如 supervisor

更多内容,参见 [[使用supervisor管理进程]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少湖说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值