S
S
serega_chem2018-12-27 11:50:19
PHP
serega_chem, 2018-12-27 11:50:19

Is it possible on RabbitMQ to handle multiple queues with one consumer?

Went through the official php/rabbitmq tutorial. To consolidate the material, I want to write a chat using websockets. I intend to use Workerman as a server.
The logic so far is this:
1. Messages get into the general exchange (with the direct type). Where routing key - user id
2. When a user connects, a queue is created and joins the exchanger using the same user id
How should all these queues be processed? The tutorial ran its own php daemon for each queue.
How to proceed in my case? Can you suggest an alternative approach)
PS: Yii2 core tool

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
serega_chem, 2018-12-27
@serega_chem

As a result of the search for a solution, the following class appeared

use PhpAmqpLib\Connection\AMQPStreamConnection;

class MessageConsumer
{
    private $channel;
    private $exchange = "message";
    
    public function __construct()
    {
        $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
        $this->channel = $connection->channel();
    }

    public function listen()
    {
        $this->channel->exchange_declare($this->exchange, 'direct', false, true, false);
        while (true) {
            $this->channel->wait();
        }
    }

    public function addQueue($queue)
    {
        $this->channel->queue_declare($queue, false, false, false, false);
        $this->channel->queue_bind($queue, $this->exchange, $queue);
        $this->channel->basic_consume($queue, '', false, true, false, false, [$this, 'processMessage']);
    }

    public function processMessage($msg)
    {
        echo "[x] {$msg->delivery_info['routing_key']} : $msg->body \n";
    }
}

The client code is something like this
use MessageConsumer;

$consumer = new MessageConsumer();
$consumer->addQueue('admin');
$consumer->addQueue('user');
$consumer->listen();

Questions immediately arise:
1. How and where to store an instance of the MessageConsumer class? Rather an instance of the current connection's AMQPChannel
2. How can I restore chat if the daemon crashes? broken connection?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question