Reconnect to the AMQP bus when the connection breaks down

This commit is contained in:
Dirk Müller 2024-06-10 17:04:25 +02:00
parent 5f228dc046
commit 2ff8ed76d0
No known key found for this signature in database

View File

@ -2,20 +2,23 @@
import json import json
from pathlib import Path from pathlib import Path
import pika import pika
import random
import sys import sys
import time
MY_TASKS_DIR = Path(__file__).parent / "tasks" MY_TASKS_DIR = Path(__file__).parent / "tasks"
def listen_events():
connection = pika.BlockingConnection(pika.URLParameters("amqps://opensuse:opensuse@rabbit.opensuse.org")) connection = pika.BlockingConnection(pika.URLParameters("amqps://opensuse:opensuse@rabbit.opensuse.org"))
channel = connection.channel() channel = connection.channel()
channel.exchange_declare(exchange='pubsub', exchange_type='topic', passive=True, durable=True) channel.exchange_declare(exchange='pubsub', exchange_type='topic', passive=True, durable=False)
result = channel.queue_declare("", exclusive=True) result = channel.queue_declare("", exclusive=True)
queue_name = result.method.queue queue_name = result.method.queue
channel.queue_bind(exchange='pubsub', channel.queue_bind(exchange='pubsub',
queue=queue_name,routing_key='#') queue=queue_name,routing_key='opensuse.obs.package.commit')
print(' [*] Waiting for logs. To exit press CTRL+C') print(' [*] Waiting for logs. To exit press CTRL+C')
@ -35,3 +38,15 @@ channel.basic_consume(queue_name,
auto_ack=True) auto_ack=True)
channel.start_consuming() channel.start_consuming()
def main():
while True:
try:
listen_events();
except pika.exceptions.ConnectionClosed:
time.sleep(random.randint(10,100))
if __name__ == '__main__':
main()