jakubkulhan / bunny

Performant pure-PHP AMQP (RabbitMQ) sync/async (ReactPHP) library
MIT License
706 stars 102 forks source link

Timer like Workerman\Timer? #95

Closed badmansan closed 4 years ago

badmansan commented 4 years ago

Good day. I am using jakubkulhan/bunny to listening RabbitMQ queue, then process the message and post result to mqtt server. The problem is that the mqtt server kick me after idle timeout. As result every time i need to connect, post message & disconnect. Pseudocode:

<?php
$bunny = new Client($connection);
$bunny->connect();
$channel = $bunny->channel();
$channel->queueDeclare('queue_name');

$channel->run(
    function (Message $message, Channel $channel, Client $bunny) {
        $result = handleMessage($message); // Handle your message here

        $mqtt = Connect($user, $pass, $host);
        $mqtt->post('topic', $result);
        $mqtt->disconnect();
    },
    'queue_name'
);

This code is very slow because of connect & disconnect on every message.

One of the solutions is set timer to ping mqtt every N seconds, something like Workerman\Timer. As far as i see jakubkulhan/bunny doesn't have that? Maybe there are other ways to do this without rewriting the current code?

badmansan commented 4 years ago

The answer in tutorial example: https://github.com/jakubkulhan/bunny/blob/master/tutorial/2-work-queues/worker-async.php

We need add code like

$loop->addPeriodicTimer(1.0, function() {
    echo 'Tick' . PHP_EOL;
});
WyriHaximus commented 4 years ago

@badmansan with a sidenote tho, the initial example in you're using the sync client, that would need the async client. Also does mqtt support heartbeats?

badmansan commented 4 years ago

Yes, mqtt protocol has PINGREQ command. It 'ping' broker and keep connection alive. I set mqtt broker timeout to 30 seconds, and timer with ping to 15. All works fine.