Rabbitmq listener using pika in django

前端 未结 1 1873
感情败类
感情败类 2021-02-10 05:10

I have a django application and I want to consume messages from a rabbit mq. I want the listener to start consuming when I start the django server.I am using pika library to con

1条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-10 06:06

    First you need to somehow run your application at the start of the django project https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.AppConfig.ready

    def ready(self):
        if not settings.IS_ACCEPTANCE_TESTING and not settings.IS_UNITTESTING:
            consumer = AMQPConsuming()
            consumer.daemon = True
            consumer.start()
    

    Further in any convenient place

    import threading
    
    import pika
    from django.conf import settings
    
    
    class AMQPConsuming(threading.Thread):
        def callback(self, ch, method, properties, body):
            # do something
            pass
    
        @staticmethod
        def _get_connection():
            parameters = pika.URLParameters(settings.RABBIT_URL)
            return pika.BlockingConnection(parameters)
    
        def run(self):
            connection = self._get_connection()
            channel = connection.channel()
    
            channel.queue_declare(queue='task_queue6')
            print('Hello world! :)')
    
            channel.basic_qos(prefetch_count=1)
            channel.basic_consume(self.callback, queue='queue')
    
            channel.start_consuming()
    

    This will help http://www.rabbitmq.com/tutorials/tutorial-six-python.html

    0 讨论(0)
提交回复
热议问题