Esempio n. 1
0
def receive_messages(
        queue: str, exchange: str, routing_key: str,
        channel: pika.adapters.blocking_connection.BlockingChannel,
        callback: ClientCallback) -> None:
    '''Receive messages from a queue'''

    channel.exchange_declare(exchange=exchange,
                             durable=True,
                             exchange_type='direct')
    channel.queue_bind(exchange=exchange, queue=queue, routing_key=routing_key)

    channel.basic_consume(queue=queue,
                          on_message_callback=callback,
                          auto_ack=True)
    channel.start_consuming()
Esempio n. 2
0
def queue_selection(
    channel: pika.adapters.blocking_connection.BlockingChannel,
    context,
    pg_username: str,
):
    """
    Callback for setting up the handler for messages published on the queue.
    @param channel: RabbitMQ channel in which to consume messages.
    @param context: context required for RabbitMQ to work properly inside a different thread than MainThread.
    @param pg_username: name of the queue and the socket in which messages are respectively read and written.
    """
    with context:

        def message_handler(ch, method, properties, body: bytes):
            """
            Callback for handling message consuming and publishing on the WebSocket.
            @param ch:
            @param method:
            @param properties:
            @param body: message body
            """
            with context:
                json = loads(body)
                msg = Message.from_dict(json)
                print(
                    f"---\nSender: {msg.sender} -- {msg.send_time}\n{msg.body}\n---\n"
                )
                socket_io.send(dumps(json), json=True, room=pg_username)

        channel.queue_declare(queue=pg_username, durable=True)

        channel.basic_consume(queue=pg_username,
                              on_message_callback=message_handler,
                              auto_ack=True)

        channel.start_consuming()