2

I used RabbitMQ before and learned that establishing a connection is expensive and that we should try to keep one connection alive to send messages. In Python, this is very straightforward because you can create a connection as an object that you can close independent of the sending or consuming logic.

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='', routing_key='', body='Hello World!')
connection.close()

The Python Qpid Proton library is sadly not very well documented. At least for a noob like me, it's hard to understand things. Looking at the example code provided on the website, you need to instantiate a MessagingHandler object for each message you want to send, which includes the opening and closing of the connection.

class MessageHandler(MessagingHandler):
    def __init__(self, message: dict):
        super(MessageHandler, self).__init__()
        self.conn_url = HOST
        self.address = ADDRESS
        self.message_body = json.dumps(message)

    def on_start(self, message):
        conn = message.container.connect(self.conn_url)
        message.container.create_sender(conn, self.address)

    def on_sendable(self, message):
        message = Message(self.message_body)
        message.sender.send(message)
        message.sender.close()
        message.connection.close()

Container(MessageHandler({"title":"test"})).run()

Now, based on this I feel a bit stupid instantiating a handler for each message I want to send, thus opening and closing a new connection every time. I feel like I must be missing out on something because I can't imagine this is the right way to do this.

Any suggestions?

0 Answers0