RabbitMQ:使用
RabbitMQ是一个消息代理,它接收和转发消息。
用的是window操作系统,按照官方教程安装过于复杂。正好最近学习了docker,于是用rabbitmq的官方镜像运行容器。本次测试下载的镜像是rabbitmq:3-management,这个镜像中内置一个管理插件,提供web图形化页面管理rabbitmq。
运行如下的命令:
docker run -d -p 15672:15672 -p 5672:5672 --name some-rabbit --hostname my-rabbit --rm rabbitmq:3-management
这个命令中需要暴露容器中两个端口号,15672用于连接到管理插件的管理页面,5672用于rabbit客户端和服务端传递消息。
浏览器访问 http://localhost:15672 即可查看web的管理页面,默认账号密码 guest/guest 。
然后按照官方的tutorial文档,用python编写producer和consumer,分别对应了sender和receiver
send.py的源码
#!/user/bin/env python # -*- coding: utf-8 -*- import pika credentials = pika.PlainCredentials('guest', 'guest') connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='Hello World') print(" [x] Sent 'Hello World!'") connection.close()
receive.py的源码
#!/user/bin/env python # -*- coding: utf-8 -*- import pika credentials = pika.PlainCredentials('guest', 'guest') connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', credentials=credentials)) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume(queue='hello', auto_ack=True, on_message_callback=callback) print(' [*] Waiting for messages. To exit press CTRL+C') channel.start_consuming()
这样就完成了producer和consumer的编写。
参考:
官方tutorial文档:https://www.rabbitmq.com/tutorials/tutorial-one-python.html
docker中rabbitmq官方镜像:https://hub.docker.com/_/rabbitmq
常见故障:https://stackoverflow.com/questions/51885880/port-forwarding-failing-for-rabbitmq-in-docker