RabbitMQ(从安装到使用)
RabbitMQ
一,RabbitMQ简单介绍:
RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。
MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。
二,安装
pip install pika
三,简单队列
1丶使用API操作RabbitMQ
基于Queue实现生产者消费者模型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import Queue
import threading message = Queue.Queue(10) def producer(i):
while True:
message.put(i) def consumer(i):
while True:
msg = message.get() for i in range(12):
t = threading.Thread(target=producer, args=(i,))
t.start() for i in range(10):
t = threading.Thread(target=consumer, args=(i,))
t.start()
对于RabbitMQ来说,生产和消费不再针对内存里的一个Queue对象,而是某台服务器上的RabbitMQ Server实现的消息队列。
# !/usr/bin/env python
# -*- coding:utf-8 -*- import pika connection = pika.BaseConnection(pika.ConnectionParameters(host='10.211.55.4')) # 封装socket逻辑部分
channel = connection.channel() # 拿到操作句柄 channel.queue_declare(queue='hello') # 通过channel创建一个队列,再给给队列取名字 channel.basic_publish(exchange='', # 通过句柄给
routing_key='hello', # 把body的数据放到名为hello的队列里去
body='Hello World!', ))
print("[x] Sent 'Hello World!")
connection.close()
生产者
# !/usr/bin/env python
# -*- coding:utf-8 -*- import pika connection = pika.BaseConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel() channel.queue_declare(queue='hello') # 创建队列 def callback(ch, method, properties, body): # 就是个回调函数
print(" [x] Received %r" % body) channel.basic_consume(callback, # 函数名;取出数据就执行这个函数
queue='hello', # 队列名
no_ack=Ture) # 无应答是(Ture);有应答(False) print(' [*] Waiting for messages.To exit press CTRL+C')
channel.start_consuming()
消费者
2丶acknowledgment消息不丢失
no-ack = False,如果消费者遇到情况(its channel is closed, connection is closed, or TCP connection is lost)挂掉了,那么,RabbitMQ会重新将该任务添加到队列中。
# !/usr/bin/env python
# -*- coding:utf-8 -*- import pika connection = pika.BaseConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel() channel.queue_declare(queue='hello') # 创建队列 def callback(ch, method, properties, body): # 就是个回调函数
print(" [x] Received %r" % body)
import time
time.sleep(10)
print('ok')
ch.basic_ack(delivery_tag=method.delivery_tag) # 调为有应答要加上的(下面的要改no_ack=False) channel.basic_qos(prefetch_count=1) channel.basic_consume(callback, # 函数名;取出数据就执行这个函数
queue='hello', # 队列名
no_ack=False) # 无应答是(Ture);有应答(False)
print(' [*] Waiting for messages.To exit press CTRL+C')
channel.start_consuming()
消费者
3丶durable消息不丢失
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel() # make message persistent
channel.queue_declare(queue='hello', durable=True) # durable=True这个参数是把数据保存到硬盘 channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!',
properties=pika.BasicProperties(
delivery_mode=2, # 传递模式从默认的1,改为2
))
print(" [x] Sent 'Hello World!'")
connection.close()
生产者
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel() # make message persistent
channel.queue_declare(queue='hello', durable=True) def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
import time
time.sleep(10)
print 'ok'
ch.basic_ack(delivery_tag = method.delivery_tag) # 把无应答调整为有应答 channel.basic_consume(callback,
queue='hello',
no_ack=False) # 改为False,表示有应答 print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
消费者
4丶消息获取顺序
默认消息队列里的数据是按照顺序被消费者拿走,例如:消费者1 去队列中获取 奇数 序列的任务,消费者1去队列中获取 偶数 序列的任务。
channel.basic_qos(prefetch_count=1) 表示谁来谁取,不再按照奇偶数排列
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel() # make message persistent
channel.queue_declare(queue='hello') def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
import time
time.sleep(10)
print 'ok'
ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count=1) # prefetch_count=1这个参数就让取的方式改变,不在顺序取数据 channel.basic_consume(callback,
queue='hello',
no_ack=False) print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
消费者
四,exchange
1、fanout模式
发布订阅
发布订阅和简单的消息队列区别在于,发布订阅会将消息发送给所有的订阅者,而消息队列中的数据被消费一次便消失。
所以,RabbitMQ实现发布和订阅时,会为每一个订阅者创建一个队列,而发布者发布消息时,会将消息放置在所有相关队列中。
exchange type = fanout
#!/usr/bin/env python
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel() # 创建交换机
channel.exchange_declare(exchange='logs', # 名字
type='fanout') # 类型 message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs', # 往名字为logs的交换机里
routing_key='', # 把数据直接放到交换机里,不用放到队列中,所以默认为空
body=message)
print(" [x] Sent %r" % message)
connection.close() # 关闭
发布者
#!/usr/bin/env python
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel() #创建交换机
channel.exchange_declare(exchange='logs',
type='fanout') # 随机创建一个队列
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue channel.queue_bind(exchange='logs', # 随机生成的队列绑定交换机
queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body):
print(" [x] %r" % body) channel.basic_consume(callback, # 在下面阻塞后,如果得到数据后才执行这个函数
queue=queue_name,
no_ack=True) channel.start_consuming() # 阻塞住,等待生产者把数据放到消费者,并监听
订阅者
图形解释:
2、dirct模式
关键字发送
RabbitMQ 还支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,
exchange 根据 关键字 判定应该将数据发送至指定队列。
exchange type = direct
#!/usr/bin/env python
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',
type='direct') severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)
print(" [x] Sent %r:%r" % (severity, message))
connection.close()
生产者
#!/usr/bin/env python
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',
type='direct') result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue severities = sys.argv[1:]
if not severities:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
sys.exit(1) for severity in severities: # 用循环是可以绑定多个队列
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key='severity') # 定义的参数(关键字) channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key='alex') 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()
消费者
图形解释:
在交换机中用一关键字,只有队列里有关键字交换机才会发送数据给绑定的队列。
3、topic
模糊匹配
在topic类型下,可以让队列绑定几个模糊的关键字,之后发送者将数据发送到exchange,exchange将传入”路由值“和 ”关键字“进行匹配,
匹配成功,则将数据发送到指定队列。exchange type = topic
# 表示可以匹配 0 个 或 多个 单词
* 表示只能匹配 一个 单词 发送者路由值 队列中
old.boy.python old.* -- 不匹配
old.boy.python old.# -- 匹配
#!/usr/bin/env python
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
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 python
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel() channel.exchange_declare(exchange='topic_logs',
type='topic') result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]...\n" % 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()
消费者
图形解释:
RabbitMQ(从安装到使用)的更多相关文章
- RabbitMQ服务安装配置
RabbitMQ是流行的开源消息队列系统,是AMQP(Advanced Message Queuing Protocol高级消息队列协议)的标准实现,用erlang语言开发.RabbitMQ据说具有良 ...
- Erlang&RabbitMQ服务安装配置
RabbitMQ是流行的开源消息队列系统,是AMQP(Advanced Message Queuing Protocol高级消息队列协议)的标准实现,用erlang语言开发.RabbitMQ据说具有良 ...
- rabbitMQ第一篇:rabbitMQ的安装和配置
在Windows下进行rabbitMQ的安装 第一步:软件安装 如果安装rabbitMQ首先安装基于erlang语言支持的OTP软件,然后在下载rabbitMQ软件进行安装(安装过程都是下一步,在此不 ...
- Linux下 RabbitMQ的安装与配置-3
一 Erlang安装 1.RabbitMQ是基于Erlang的,所以首先必须配置Erlang环境. 从Erlang的官网http://www.erlang.org/download.html 下载最 ...
- 【linux环境下】RabbitMq的安装和监控插件安装
[注意安装过程中,提示某些命令not found,直接yum isntall一下就好了] 以下是我在CentOS release 6.4下亲测成功的. RabbitMq的安装: RabbitMQ是 ...
- 【windows环境下】RabbitMq的安装和监控插件安装
RabbitMq的安装: RabbitMQ是基于Erlang的,所以必须先配置Erlang环境. 下载Erlang,地址:http://www.erlang.org/download/otp_win3 ...
- gcc, numpy, rabbitmq等安装升级总结
1. 公司在下面目录安装了gcc-4.8.2,以支持c++11,可以通过在bashrc中添加来实现: PATH=/opt/compiler/gcc-4.8.2/bin:$PATH 2. 公司环境切换到 ...
- Linux下 RabbitMQ的安装与配置
以下教程摘录自互联网并做了适当修改,测试的rabbitmq 版本为:rabbitmq-server-generic-unix-3.5.6 各版本之间会有差异!!! 一 Erlang安装 Rabbit ...
- Linux rabbitmq的安装和安装amqp的php插件
RabbitMQ是一个消息代理.它的核心原理非常简单:接收和发送消息.你可以把它想像成一个邮局:你把信件放入邮箱,邮递员就会把信件投递到你的收件人处.在这个比喻中,RabbitMQ是一个邮箱.邮局.邮 ...
- RabbitMQ windows安装官方文档翻译!
RabbitMQ Windows安装和配置 下载地址 官网windows下载地址: http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.10/r ...
随机推荐
- thinkPHP 模板中变量的使用
一.变量输出 1.标量输出(普通) 2.数组输出 {$name[1]} {$name['k2'] ...
- js bool true false 比较
.想到一个好玩的,运行如下 javascript : if ('0') alert("'0' is true"); if ('0' == false) alert(" ...
- HDU-4861-Couple doubi(数学题,难懂!难懂!)
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=4861 这个题只能说没弄懂,感觉很难,看博客也看不懂,只能,多看几次,看能不能有所突破了. 代码的话只有 ...
- TIMESTAMP和DATETIME哪个好
日期范围 TIMESTAMP 支持从'1970-01-01 00:00:01′ 到 '2038-01-19 03:14:07′ UTC. 这个时间可能对目前正在工作的人来说没什么问题,可以坚持到我们退 ...
- adb server无法启动方法,结束占用端口的进程
adb server is out of date. killing...ADB server didn't ACK* failed to start daemon *error: unknown ...
- {}typeof string转为 obj json
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.11.3/jquer ...
- 关于flash擦除的方法
一般的Flash,只允许写时将1变成0,而不允许0变成1:仅当擦除时将0变成1.所以写全0xff是没什么意义的 以前对flash只能进行一次写很困惑,这句话解释了原因. norflash就是 对bit ...
- mac下为gdb创建证书赋权其调试其它应用
1 使用/Applications/Utilities/Keychain Access.app创建证书 钥匙串访问->证书助理->创建证书 给证书随笔取一个名字,身份类型"自签名 ...
- Exiting the Matrix: Introducing Metasploit's Hardware Bridge
Metasploit is an amazing tool. You can use it to maneuver through vast networks, pivoting through se ...
- Webservice_常用
官网示例: http://cxf.apache.org/docs/writing-a-service-with-spring.html http://cxf.apache.org/docs/jax-r ...