0

I'm trying to set up RabbitMQ in Docker-Compose with two little Python scripts. One creating and sending a message (Producer) and the other receiving and consuming the message (Consumer). The producer works fine. As you can read below, the subscriber(consumer) authenticates and connects to rabbitmq as well as the producer.

(192.168.128.3:55484 -> 192.168.128.2:5672): user 'producer' authenticated and granted access to vhost 'vhost'

rabbitmq | 2021-07-28 13:11:50.636 [info] <0.1181.0> accepting AMQP connection <0.1181.0> (192.168.128.4:45802 -> 192.168.128.2:5672)

rabbitmq | 2021-07-28 13:11:50.640 [info] <0.1181.0> connection <0.1181.0> (192.168.128.4:45802 -> 192.168.128.2:5672): user 'subscriber' authenticated and granted access to vhost 'vhost'

rabbitmq | 2021-07-28 13:11:55.614 [info] <0.1168.0> closing AMQP connection <0.1168.0> (192.168.128.3:55484 -> 192.168.128.2:5672, vhost: 'vhost', user: 'producer')

rabbitmq | 2021-07-28 13:11:55.614 [info] <0.1196.0> Closing all channels from connection '192.168.128.3:55484 -> 192.168.128.2:5672' because it has been closed


producer | [x] Sent 'hello consumer'

In the Management UI I can see that the connection and the channel were also created and that the consumer is listening.

Management UI Picture

My consumer script:

import pika
import jwt
from time import sleep
import sys

def callback(ch, method, properties, body):
    sys.stderr.write(str(body))
    ch.basic_ack(delivery_tag = method.delivery_tag)

encoded_jwt = jwt.encode({
  "sub": "subscriber",
  "aud": "abamsgq",
  "scope":"abamsgq.read:*/*/*"},
  "secret",
  algorithm="HS256",
  headers={"kid":"key1","algorithm":"HS256","kty":"MAC"})

credentials = pika.PlainCredentials('subscriber', encoded_jwt)

for x in range(0,5):
  try:
    connection = pika.BlockingConnection(
            pika.ConnectionParameters('rabbitmq',
                                        5672,
                                        'vhost',
                                        credentials))
    channel = connection.channel()
    channel.basic_consume(queue='queue1',
                  on_message_callback=callback)

    sys.stderr.write("Waiting for messages. To exit press CTRL+C")

    channel.start_consuming()
    exception = False

  except Exception:
    exception = True
    #sleep(5)

if exception:
  # Error message
  sys.stderr.write("Did not connect!\n")
  sys.exit(1)

The consumer console is supposed to write the body of the message as well as "Waiting for messages. To exit press CTRL+C". Appreciate your help!

  • 2
    It was not RabbitMQ's problem but rather Docker. For some reason it couldn't print anything on docker while running a loop in the script. Solution: use print function and flush: print(" ", flush = True) to force print. https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function – hammerjunge Jul 29 '21 at 08:57

0 Answers0