__init__.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import logging
  2. import tomllib
  3. import pika
  4. from .worker import handle_message
  5. logger = logging.getLogger(__name__)
  6. def start_consumer(name, queue, config):
  7. connection = pika.BlockingConnection(
  8. pika.ConnectionParameters(
  9. host=config['host'], port=config['port'],
  10. credentials=pika.PlainCredentials(
  11. config['user'], config['password']),
  12. virtual_host=config['virtual-host']))
  13. channel = connection.channel()
  14. def callback(ch, method, properties, body):
  15. logger.info("received message(%s,%s)",
  16. properties.message_id, properties.content_type)
  17. handle_message(properties.message_id, properties.content_type, body)
  18. channel.basic_consume(
  19. queue=queue, on_message_callback=callback, auto_ack=True)
  20. logger.info('start a consumer(%s) for queue(%s)', name, queue)
  21. channel.start_consuming()
  22. def launch(name, queue, config_file):
  23. logger.debug('load configuration from %s', config_file)
  24. with open(config_file, "rb") as config_fd:
  25. config = tomllib.load(config_fd)
  26. start_consumer(name, queue, config['rabbitmq'])