当前位置:   article > 正文

Python RabbitMQ 消息队列

python 实现rabbitmq消息队列
WechatIMG91.jpeg

环境

  • Ubuntu 16.04.1

  • Python 3.5.2

安装RabbitMQServer

  • 更新软件源
$ apt-get update
  • 安装 rabbitmq-server
$ apt-get install -y rabbitmq-server
  • 安装 pika
$ pip3 install pika

用来实现 python 与 rabbitmq 的对接。

管理RabbitMQServer

  • 启动
$ service rabbitmq-server start
  • 关闭
$ service rabbitmq-server stop
  • 查看状态
$ service rabbitmq-server status
  • 调整系统限制
  1. $ cat /etc/default/rabbitmq-server
  2. # This file is sourced by /etc/init.d/rabbitmq-server. Its primary
  3. # reason for existing is to allow adjustment of system limits for the
  4. # rabbitmq-server process.
  5. #
  6. # Maximum number of open file handles. This will need to be increased
  7. # to handle many simultaneous connections. Refer to the system
  8. # documentation for ulimit (in man bash) for more information.
  9. #
  10. ulimit -n 1024

编辑 /etc/default/rabbitmq-server 中的 ulimit 参数,默认1024。

  • 日志
  1. $ ls /var/log/rabbitmq
  2. rabbit@VM-2-14-ubuntu.log startup_err
  3. rabbit@VM-2-14-ubuntu-sasl.log startup_log

工作队列模式

61e677960a9dc_61e677960a9d6.png
  • 创建 new_task.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. import sys
  4. connection = pika.BlockingConnection(pika.ConnectionParameters(
  5. host='localhost'))
  6. channel = connection.channel()
  7. # 持久化一个队列,名为 task_queue
  8. channel.queue_declare(queue='task_queue', durable=True)
  9. message = ' '.join(sys.argv[1:]) or "No new task"
  10. channel.basic_publish(exchange='',
  11. routing_key='task_queue',
  12. body=message,
  13. properties=pika.BasicProperties(
  14. # 消息持久化
  15. delivery_mode = 2,
  16. ))
  17. print(" [x] Sent %r" % message)
  18. # 关闭连接
  19. connection.close()
  • 创建 worker.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. import time
  4. connection = pika.BlockingConnection(pika.ConnectionParameters(
  5. host='localhost'))
  6. channel = connection.channel()
  7. channel.queue_declare(queue='task_queue', durable=True)
  8. print(" [*] Waiting for messages. To exit press CTRL+C")
  9. def callback(ch, method, properties, body):
  10. print(" [x] Received %r" % body)
  11. time.sleep(body.count(b'.') )
  12. print(" [x] Done")
  13. ch.basic_ack(delivery_tag = method.delivery_tag)
  14. channel.basic_qos(prefetch_count=1)
  15. channel.basic_consume(queue='task_queue',
  16. on_message_callback=callback)
  17. channel.start_consuming()
  • 执行
  1. # 终端1,发布新任务
  2. $ python3 new_task.py eating
  3. [x] Sent 'eating'
  4. $ python3 new_task.py drinking
  5. [x] Sent 'drinking'
  6. $ python3 new_task.py playing
  7. [x] Sent 'playing'
  8. # 终端2,添加工作者
  9. $ python3 worker.py
  10. [*] Waiting for messages. To exit press CTRL+C
  11. [x] Received b'eating'
  12. [x] Done
  13. [x] Received b'drinking'
  14. [x] Done
  15. [x] Received b'playing'
  16. [x] Done

扇形交换机

61e686ab09d66_61e686ab09d5b.png
  • 创建 send_log.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. import sys
  4. connection = pika.BlockingConnection(
  5. pika.ConnectionParameters(host='localhost'))
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='logs', exchange_type='fanout')
  8. message = ' '.join(sys.argv[1:]) or "info: Hello World!"
  9. channel.basic_publish(exchange='logs', routing_key='', body=message)
  10. print(" [x] Sent %r" % message)
  11. connection.close()
  • 创建 receive_logs.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. connection = pika.BlockingConnection(
  4. pika.ConnectionParameters(host='localhost'))
  5. channel = connection.channel()
  6. channel.exchange_declare(exchange='logs', exchange_type='fanout')
  7. result = channel.queue_declare(queue='', exclusive=True)
  8. queue_name = result.method.queue
  9. channel.queue_bind(exchange='logs', queue=queue_name)
  10. print(' [*] Waiting for logs. To exit press CTRL+C')
  11. def callback(ch, method, properties, body):
  12. print(" [x] %r" % body)
  13. channel.basic_consume(
  14. queue=queue_name, on_message_callback=callback, auto_ack=True)
  15. channel.start_consuming()
  • 执行
  1. # 终端1,接收日志
  2. $ python3 receive_logs.py
  3. [*] Waiting for logs. To exit press CTRL+C
  4. [x] b'eating'
  5. # 终端2,接收日志
  6. $ python3 receive_logs.py
  7. [*] Waiting for logs. To exit press CTRL+C
  8. [x] b'eating'
  9. # 终端3,发送日志
  10. $ python3 new_task.py eating
  11. [x] Sent 'eating'

直连交换机

61e68ad22bf39_61e68ad22bf33.png
  • 创建 send_log_direct.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. import sys
  4. connection = pika.BlockingConnection(
  5. pika.ConnectionParameters(host='localhost'))
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
  8. severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
  9. message = ' '.join(sys.argv[2:]) or 'Hello World!'
  10. channel.basic_publish(
  11. exchange='direct_logs', routing_key=severity, body=message)
  12. print(" [x] Sent %r:%r" % (severity, message))
  13. connection.close()
  • 创建 receive_logs_direct.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. import sys
  4. connection = pika.BlockingConnection(
  5. pika.ConnectionParameters(host='localhost'))
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='direct_logs', exchange_type='direct')
  8. result = channel.queue_declare(queue='', exclusive=True)
  9. queue_name = result.method.queue
  10. severities = sys.argv[1:]
  11. if not severities:
  12. sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
  13. sys.exit(1)
  14. for severity in severities:
  15. channel.queue_bind(
  16. exchange='direct_logs', queue=queue_name, routing_key=severity)
  17. print(' [*] Waiting for logs. To exit press CTRL+C')
  18. def callback(ch, method, properties, body):
  19. print(" [x] %r:%r" % (method.routing_key, body))
  20. channel.basic_consume(
  21. queue=queue_name, on_message_callback=callback, auto_ack=True)
  22. channel.start_consuming()
  • 执行
  1. # 终端1,接收日志
  2. $ python3 receive_logs_direct.py error
  3. [*] Waiting for logs. To exit press CTRL+C
  4. [x] 'error':b'playing
  5. # 终端2,接收日志
  6. $ python3 receive_logs_direct.py info
  7. [*] Waiting for logs. To exit press CTRL+C
  8. [x] 'info':b'watching'
  9. # 终端3,发送日志
  10. $ python3 send_log_direct.py info watching
  11. [x] Sent 'info':'watching'
  12. $ python3 send_log_direct.py error playing
  13. [x] Sent 'error':'playing'

主题交换机

61e690149f79f_61e690149f79a.png
  • 创建 send_log_topic.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. import sys
  4. connection = pika.BlockingConnection(
  5. pika.ConnectionParameters(host='localhost'))
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
  8. routing_key = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info'
  9. message = ' '.join(sys.argv[2:]) or 'Hello World!'
  10. channel.basic_publish(
  11. exchange='topic_logs', routing_key=routing_key, body=message)
  12. print(" [x] Sent %r:%r" % (routing_key, message))
  13. connection.close()
  • 创建 receive_logs_topic.py,代码如下
  1. #!/usr/bin/env python3
  2. import pika
  3. import sys
  4. connection = pika.BlockingConnection(
  5. pika.ConnectionParameters(host='localhost'))
  6. channel = connection.channel()
  7. channel.exchange_declare(exchange='topic_logs', exchange_type='topic')
  8. result = channel.queue_declare('', exclusive=True)
  9. queue_name = result.method.queue
  10. binding_keys = sys.argv[1:]
  11. if not binding_keys:
  12. sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
  13. sys.exit(1)
  14. for binding_key in binding_keys:
  15. channel.queue_bind(
  16. exchange='topic_logs', queue=queue_name, routing_key=binding_key)
  17. print(' [*] Waiting for logs. To exit press CTRL+C')
  18. def callback(ch, method, properties, body):
  19. print(" [x] %r:%r" % (method.routing_key, body))
  20. channel.basic_consume(
  21. queue=queue_name, on_message_callback=callback, auto_ack=True)
  22. channel.start_consuming()
  • 执行
  1. # 终端1,发送日志
  2. $ python3 send_log_topic.py "quick.orange.rabbit"
  3. [x] Sent 'quick.orange.rabbit':"quick.orange.rabbit'
  4. $ python3 send_log_topic.py "lazy.pink.rabbit"
  5. [x] Sent 'quick.orange.rabbit':'lazy.pink.rabbit'
  6. # 终端2,接收日志
  7. $ python3 receive_logs_topic.py "*.orange.*"
  8. [*] Waiting for logs. To exit press CTRL+C
  9. [x] 'quick.orange.rabbit':b'lazy.pink.rabbit'
  10. # 终端3,接收日志
  11. $ python3 receive_logs_topic.py "*.*.rabbit"
  12. [*] Waiting for logs. To exit press CTRL+C
  13. [x] 'quick.orange.rabbit':b'lazy.pink.rabbit'
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/480970
推荐阅读
相关标签
  

闽ICP备14008679号