Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python之RabbitMQ

RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。 安装RabbitMQ: 
12345678910111213141516171819安装配置epel源:(详见http://www.cnblogs.com/ernest-zhang/p/5714434.html安装erlang:yum -y install erlang注:安装erlang的时候碰到    Error: Package: erlang-erts-R14B-04.3.el6.i686 (epel)           Requires: libz.so.1(ZLIB_1.2.2[root@localhost ~]# yum whatprovides libz.so.1Loaded plugins: rhnpluginThis system is not registered with RHN.RHN support will be disabled.zlib-1.2.3-25.el6.i686 : The zlib compression and decompression library #提供压缩与解压缩库Repo        : localMatched from:Other     : libz.so.1检查发现应该是zlib的版本太老了,从网上下载最新的zlib-1.2.8-10.fc24.i686,然后使用RPM安装后解决。下载地址:http://www.zlib.net/  #zlib官网http://rpmfind.net/linux/rpm2html/search.php?query=zlib    #zlib下载网站安装rabbitMQ:yum -y install rabbitmq-server
service rabbitmq-server start/stop 启动和停止rabbitmq安装API,然后可以基于API操作rabbitmq 
1234567pip install pikaoreasy_install pikaor源码  https://pypi.python.org/pypi/pika
Python 操作RabbitMQ发布端:
1234567import pikaconnection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))    #服务器地址channel=connection.channel()channel.queue_declare(queue="Hi") #如果有队列,略过;如果没有,创建队列channel.basic_publish(exchange="",routing_key="cc",body="hello!world!!!")print"[x] sent "hello,world!""connection.close()
接收端:
12345678910111213141516import pika#创建一个连接对象,绑定rabbitmq的IPconnection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))#创建一个频道对象channel=connection.channel()#频道中声明指定queue,如果MQ中没有指定queue就创建,如果有,则略过channel.queue_declare(queue="Hi"#定义回调函数def callback(ch,method,properties,body):    print"[x] Recieved %r"%body)    # channel.close()#no_ack=Fales:表示消费完以后不主动把状态通知rabbitmq,callback:回调函数,queue:指定队列channel.basic_consume(callback,queue="Hi",no_ack=True# channel.basic_consume(callback,queue="cc")print"[*] Waiting for msg"channel.start_consuming()
1、acknowledgment 消息不丢失no-ack = False,如果消费者遇到情况(its channel is closed, connection is closed, or TCP connection is lost)挂掉了,那么,RabbitMQ会重新将该任务添加到队列中。
  • 回调函数中的ch.basic_ack(delivery_tag=method.delivery_tag)
  • basic_comsume中的no_ack=False
import pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.queue_declare(queue="Hi")# 定义回调函数def callback(ch, method, properties, body):print("[x] Recieved %r" % body)# channel.close()ch.basic_ack(delivery_tag=method.delivery_tag)# no_ack=Fales:表示消费完以后不主动把状态通知rabbitmqchannel.basic_consume(callback, queue="Hi",no_ack=False)print("[*] Waiting for msg")channel.start_consuming()

durable 消息不丢失

消息生产者端发送消息时挂掉了,消费者接消息时挂掉了,以下方法会让RabbitMQ重新将该消息添加到队列中:
  • 回调函数中的ch.basic_ack(delivery_tag=method.delivery_tag),消费端需要做的
  • basic_comsume中的no_ack=False,消费端需要做的
  • 发布消息端的basic_publish添加参数properties=pika.BasicProperties(delivery_mode=2),生产者端需要做的
import pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.queue_declare(queue="Hi")# 如果有,略过;如果没有,创建队列channel.basic_publish(exchange="",routing_key="Hi",body="hello!world!!!",properties=pika.BasicProperties(delivery_mode=2)) #消息持久化print("[x] sent "hello,world!"")connection.close() 生产者 import pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.queue_declare(queue="Hi")# 定义回调函数def callback(ch, method, properties, body):print("[x] Recieved %r" % body)# channel.close()ch.basic_ack(delivery_tag=method.delivery_tag)# no_ack=Fales:表示消费完以后不主动把状态通知rabbitmqchannel.basic_consume(callback, queue="Hi",no_ack=True)print("[*] Waiting for msg")channel.start_consuming()消费者

消息获取顺序

默认消息队列里的数据是按照顺序被消费者拿走,例如:消费者1去队列中获取 奇数 序列的任务,消费者2去队列中获取 偶数 序列的任务。但有大部分情况下,消息队列后端的消费者服务器的处理能力是不相同的,这就会出现有的服务器闲置时间较长,资源浪费的情况,那么,我们就需要改变默认的消息队列获取顺序!channel.basic_qos(prefetch_count=1) 表示谁来谁取,不再按照奇偶数排列,这是消费者端需要做的import pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.queue_declare(queue="Hi")# 定义回调函数def callback(ch, method, properties, body):print("[x] Recieved %r" % body)# channel.close()ch.basic_ack(delivery_tag=method.delivery_tag)channel.basic_qos(prefetch_count=1) #改变默认获取顺序,谁来谁取# no_ack=Fales:表示消费完以后不主动把状态通知rabbitmqchannel.basic_consume(callback, queue="Hi",no_ack=True)print("[*] Waiting for msg")channel.start_consuming()消费者

发布和订阅

发布订阅和简单的消息队列区别在于,发布订阅会将消息发送给所有的订阅者,而消息队列中的数据被消费一次便消失。所以,RabbitMQ实现发布和订阅时,会为每一个订阅者创建一个队列,而发布者发布消息时,会将消息放置在所有相关队列中。RabbitMQ中,所有生产者提交的消息都由Exchange来接受,然后Exchange按照特定的策略转发到Queue进行存储 。RabbitMQ提供了四种Exchange:fanout,direct,topic,headerheader模式在实际使用中较少,只对前三种模式进行比较。exchange type = fanout任何发送到Fanout Exchange的消息都会被转发到与该Exchange绑定(Binding)的所有Queue上。1.可以理解为路由表的模式2.这种模式不需要RouteKey3.这种模式需要提前将Exchange与Queue进行绑定,一个Exchange可以绑定多个Queue,一个Queue可以同多个Exchange进行绑定。4.如果接受到消息的Exchange没有与任何Queue绑定,则消息会被抛弃。import pikaconnection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.exchange_declare(exchange="logs_fanout",type="fanout")msg="456"channel.basic_publish(exchange="logs_fanout",routing_key="",body=msg)print("开始发送:%s"%msg)connection.close() 生产者 import pikaconnection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.exchange_declare(exchange="logs_fanout",type="fanout")#随机创建队列result=channel.queue_declare(exclusive=True)queue_name=result.method.queue#绑定相关队列名称channel.queue_bind(exchange="logs_fanout",queue=queue_name)def callback(ch,method,properties,body):print("[x] %r"%body)channel.basic_consume(callback,queue=queue_name,no_ack=True)channel.start_consuming()消费者 关键字任何发送到Direct Exchange的消息都会被转发到RouteKey中指定的Queue。1.一般情况可以使用rabbitMQ自带的Exchange:”"(该Exchange的名字为空字符串,下文称其为default Exchange)。 2.这种模式下不需要将Exchange进行任何绑定(binding)操作 3.消息传递时需要一个“RouteKey”,可以简单的理解为要发送到的队列名字。 4.如果vhost中不存在RouteKey中指定的队列名,则该消息会被抛弃。import pikaconnection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.exchange_declare(exchange="logs_direct_test1",type="direct")serverity="error"msg="123"channel.basic_publish(exchange="logs_direct_test1",routing_key=serverity,body=msg)print("开始发送:%r:%r"%(serverity,msg))connection.close()生产者import pikaconnection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.exchange_declare(exchange="logs_direct_test1",type="direct")#随机创建队列result=channel.queue_declare(exclusive=True)queue_name=result.method.queueserverities=["error","info","warning",]for serverity in serverities:channel.queue_bind(exchange="logs_direct_test1",queue=queue_name,routing_key=serverity)print("[***] 开始接受消息!")def callback(ch,method,properties,body):print("[x] %r:%r"%(method.routing_key,body))channel.basic_consume(callback,queue=queue_name,no_ack=True)channel.start_consuming()消费者1import pikaconnection=pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.exchange_declare(exchange="logs_direct_test1",type="direct")#随机创建队列result=channel.queue_declare(exclusive=True)queue_name=result.method.queueserverities=["error",]for serverity in serverities:channel.queue_bind(exchange="logs_direct_test1",queue=queue_name,routing_key=serverity)print("[***] 开始接受消息!")def callback(ch,method,properties,body):print("[x] %r:%r"%(method.routing_key,body))channel.basic_consume(callback,queue=queue_name,no_ack=True)channel.start_consuming()消费者2模糊订阅任何发送到Topic Exchange的消息都会被转发到所有关心RouteKey中指定话题的Queue上1.这种模式较为复杂,简单来说,就是每个队列都有其关心的主题,所有的消息都带有一个“标题”(RouteKey),Exchange会将消息转发到所有关注主题能与RouteKey模糊匹配的队列。 2.这种模式需要RouteKey,也许要提前绑定Exchange与Queue。 3.在进行绑定时,要提供一个该队列关心的主题,如“#.log.#”表示该队列关心所有涉及log的消息(一个RouteKey为”MQ.log.error”的消息会被转发到该队列)。 4.“#”表示0个或若干个关键字,“*”表示一个关键字。如“log.*”能与“log.warn”匹配,无法与“log.warn.timeout”匹配;但是“log.#”能与上述两者匹配。 5.同样,如果Exchange没有发现能够与RouteKey匹配的Queue,则会抛弃此消息。#!/usr/bin/env pythonimport pikaimport sysconnection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.exchange_declare(exchange="topic_logs", type="topic")routing_key = sys.argv[1] if len(sys.argv) > 1 else "anonymous.info"message = " ".join(sys.argv[2:]) or "Hello World!"channel.basic_publish(exchange="topic_logs",routing_key=routing_key,body=message)print(" [x] Sent %r:%r" % (routing_key, message))connection.close() 生产者 #!/usr/bin/env pythonimport pikaimport sysconnection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.0.74"))channel = connection.channel()channel.exchange_declare(exchange="topic_logs", type="topic")result = channel.queue_declare(exclusive=True)queue_name = result.method.queuebinding_keys = sys.argv[1:]if not binding_keys:sys.stderr.write("Usage: %s [binding_key]... " % sys.argv[0])sys.exit(1)for binding_key in binding_keys:channel.queue_bind(exchange="topic_logs", queue=queue_name, routing_key=binding_key)print(" [*] Waiting for logs. To exit press CTRL+C")def callback(ch, method, properties, body):print(" [x] %r:%r" % (method.routing_key, body))channel.basic_consume(callback,queue=queue_name,no_ack=True)channel.start_consuming() CentOS 5.6 安装RabbitMQ http://www.linuxidc.com/Linux/2013-02/79508.htmRabbitMQ客户端C++安装详细记录 http://www.linuxidc.com/Linux/2012-02/53521.htm用Python尝试RabbitMQ http://www.linuxidc.com/Linux/2011-12/50653.htmRabbitMQ集群环境生产实例部署 http://www.linuxidc.com/Linux/2012-10/72720.htmUbuntu下PHP + RabbitMQ使用 http://www.linuxidc.com/Linux/2010-07/27309.htm在CentOS上安装RabbitMQ流程 http://www.linuxidc.com/Linux/2011-12/49610.htmRabbitMQ概念及环境搭建 http://www.linuxidc.com/Linux/2014-12/110449.htmRabbitMQ入门教程  http://www.linuxidc.com/Linux/2015-02/113983.htmRabbitMQ 的详细介绍:请点这里
RabbitMQ 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-07/133729.htm