RabbitMQ消息队列:默认为消息轮循模式,按client端启动是顺序接收

server端

 import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()#管道 #声明queue
#channel.queue_declare(queue='hello')#队列名 hello
channel.queue_declare(queue='hello',durable=True)#队列名 hello,持久化队列 for i in range(10): channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!%s'%i,
properties=pika.BasicProperties(delivery_mode=2))
print(" [x] Sent 'Hello World!'",i)
connection.close()

client端

 import pika,time

 connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
#channel.queue_declare(queue='hello')
channel.queue_declare(queue='hello',durable=True)#队列名 hello,持久化队列 def callback(ch, method, properties, body):#回调函数
print('接收消息中…………')
time.sleep(1)
print(" [x] Received %r" % body)
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1)#同时只处理一个消息
channel.basic_consume(callback,#接收到消息调用回调函数 callback
queue='hello',
#no_ack=True
) print(' [*] 接收消息中. To exit press CTRL+C')
channel.start_consuming()#启动消息接收

消息持久化

server端

 import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()#管道 #声明queue
channel.queue_declare(queue='hello2',durable=True)#队列名 hello
#channel.queue_declare(queue='hello2',durable=True)#队列名 hello,持久化队列 channel.basic_publish(exchange='',
routing_key='hello2',
body='Hello World!%s---->')
print(" [x] Sent 'Hello World!'")
connection.close()

client端

 import pika,time

 connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello2')#服务端与客户端的设置需一致,不然会报错
#channel.queue_declare(queue='hello2',durable=True)#队列名 hello,持久化队列 def callback(ch, method, properties, body):#回调函数
print('接收消息中…………')
time.sleep(5)
print(" [x] Received %r" % body)
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1)#同时只处理一个消息
channel.basic_consume(callback,#接收到消息调用回调函数 callback
queue='hello2',
#no_ack=True
) print(' [*] 接收消息中. To exit press CTRL+C')
channel.start_consuming()#启动消息接收

fanout广播模式:实时发送,发送时,如果client端没启动将无法收到消息

server端

 import pika,sys,time
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()#管道 #声明queue 广播模式不用声明队列
#channel.queue_declare(queue='hello')#队列名 hello
#channel.queue_declare(queue='hello',durable=True)#队列名 hello,持久化队列 argv=input('输入消息')
msg=''.join(sys.argv[1:]) or 'info:消息默认发送………'
for i in range(10):
time.sleep(1)
channel.basic_publish(exchange='logs',#绑定频道
#routing_key='hello',
routing_key='',
body=msg+str(i),
#properties=pika.BasicProperties(delivery_mode=2)#持久化 广播不能使用
)
print(msg,i)
#connection.close()

client端

 import pika,time

 connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
#channel.queue_declare(queue='hello2')#服务端与客户端的设置需一致,不然会报错
#channel.queue_declare(queue='hello2',durable=True)#队列名 hello,持久化队列
channel.exchange_declare(exchange='logs',#绑定频道
type='fanout')#接收类型
reult=channel.queue_declare(exclusive=True)#随机生成唯一的队列名,会在消息接收后自动删除
queuename=reult.method.queue#队列名 自动生成
channel.queue_bind(exchange='logs',#先要绑定频道
queue=queuename
) def callback(ch, method, properties, body):#回调函数
print('接收消息中…………')
#time.sleep(5)
print(" [x] Received %r" % body.decode())
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1)#同时只处理一个消息
channel.basic_consume(callback,#接收到消息调用回调函数 callback
queue=queuename,
#no_ack=True
) print(' [*] 接收消息中. To exit press CTRL+C') channel.start_consuming()#启动消息接收

direct广播模式:分级别发送消——客户端可以按级别接收

server端

 import pika,sys,time
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()#管道 severity = sys.argv[1] if len(sys.argv) > 1 else 'info'#启动参数 默认无参数为 info 级别
msg=''.join(sys.argv[2:]) or 'info:消息默认发送………'#启动参数 为空,发默认消息
for i in range(10):
time.sleep(1)
channel.basic_publish(exchange='direct_logs',#绑定频道
routing_key=severity,#默认的消息队列级别
body=msg+str(i),
#properties=pika.BasicProperties(delivery_mode=2)#持久化 广播不能使用
)
print(msg,severity)
connection.close()

client端

 import pika,time,sys

 connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',#定义一个接收的频道
type='direct') reult=channel.queue_declare(exclusive=True)#随机生成唯一的队列名,会在消息接收后自动删除
queuename=reult.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=queuename,
routing_key=severity) def callback(ch, method, properties, body):#回调函数
print('接收消息中…………')
#time.sleep(5)
print(" [x] Received %r" % body.decode())
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1)#同时只处理一个消息
channel.basic_consume(callback,#接收到消息调用回调函数 callback
queue=queuename,
#no_ack=True
) print(' [*] 接收消息中. To exit press CTRL+C') channel.start_consuming()#启动消息接收

topic细致消息过滤

server端

 import pika,sys,time
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()#管道 #severity = sys.argv[1] if len(sys.argv) > 1 else 'info'#启动参数 默认无参数为 info 级别
routing_key= sys.argv[1] if len(sys.argv) > 1 else 'anorrymous.info'#启动参数 默认无参数为 info 级别
msg=''.join(sys.argv[2:]) or 'info:消息默认发送………'#启动参数 为空,发默认消息
for i in range(10):
time.sleep(1)
channel.basic_publish(exchange='direct_logs',#绑定频道
#routing_key=severity,#默认的消息队列级别
routing_key=routing_key,#默认的消息队列级别
body=msg+str(i),
#properties=pika.BasicProperties(delivery_mode=2)#持久化 广播不能使用
)
#print(msg,severity)
print(msg,routing_key)
connection.close()

client端

 import pika,time,sys

 connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',#定义一个接收的频道
type='topic') reult=channel.queue_declare(exclusive=True)#随机生成唯一的队列名,会在消息接收后自动删除
queuename=reult.method.queue#队列名 自动生成 #severities = sys.argv[1:]
binding_key = sys.argv[1:]
#if not severities:
if not binding_key:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])#启动接收的消息级别
sys.exit(1) #for severity in severities:#循环接收各级别的消息
for severity in binding_key:#循环接收各级别的消息
channel.queue_bind(exchange='direct_logs',
queue=queuename,
routing_key=severity) def callback(ch, method, properties, body):#回调函数
print('接收消息中…………')
#time.sleep(5)
print(" [x] Received %r" % body.decode())
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1)#同时只处理一个消息
channel.basic_consume(callback,#接收到消息调用回调函数 callback
queue=queuename,
#no_ack=True
) print(' [*] 接收消息中. To exit press CTRL+C') channel.start_consuming()#启动消息接收

RPC模式:结果返回

server端

 import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))#生成消息对队 channel = connection.channel()#生成管道 channel.queue_declare(queue='rpc_queue')#消息收接的模式 def fib(n):#计算函数——非波那
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2) def on_request(ch, method, props, body):#回调函数
n = int(body) print(" [.] fib(%s)" % n)
response = fib(n)#调用计算函数 ch.basic_publish(exchange='',
routing_key=props.reply_to,#收消息的队列
properties=pika.BasicProperties(correlation_id =props.correlation_id),#返回消息的队列
body=str(response))#返回结果数据
ch.basic_ack(delivery_tag = method.delivery_tag)##确保消息被 客户端接收 channel.basic_qos(prefetch_count=1)#同时只处理一个消息
channel.basic_consume(on_request, queue='rpc_queue')#接收消息,自动调用回调函数 print(" [x] Awaiting RPC requests")
channel.start_consuming()#开始接收

client端

 import pika
import uuid class FibonacciRpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))#生成连接的服务端 ip self.channel = self.connection.channel()#创建一个管道 result = self.channel.queue_declare(exclusive=True)#随机生成一个队列,收消息后自动删除
self.callback_queue = result.method.queue#赋于管道 变量 self.channel.basic_consume(self.on_response,#回调函数
no_ack=True,#不用服务端确认本条消息
queue=self.callback_queue)#随机生的队列 def on_response(self, ch, method, props, body):#回调函数
if self.corr_id == props.correlation_id:#判断服务端返回的队列名是否与当前所生成的队列名一致
self.response = body# 将服务端的结果赋于返回来的结果变量 def call(self, n):#发送消息的函数
self.response = None#初始返回结果为空
self.corr_id = str(uuid.uuid4())#生成一个服务端返回消息的队列名
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',#确认为rpc模式 实时发送
properties=pika.BasicProperties(
reply_to = self.callback_queue,#发送的管道队列名
correlation_id = self.corr_id,#发送给服务端,用于返回消息的队列名
),
body=str(n))#发送的内容数据
while self.response is None:
self.connection.process_data_events()#非阻塞模式接收消息
print('没有返回消息……')
return int(self.response)#返回结果 fibonacci_rpc = FibonacciRpcClient()#生成一个实例 print(" [x] Requesting fib(10)")
response = fibonacci_rpc.call(10)#调用发送消息的函数
print(" [.] Got %r" % response)#打印结果

python第六十天-----RabbitMQ的更多相关文章

  1. 孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2

    孤荷凌寒自学python第六十九天学习并实践beautifulsoup对象用法2 (完整学习过程屏幕记录视频地址在文末) 今天继续学习beautifulsoup对象的属性与方法等内容. 一.今天进一步 ...

  2. 孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5

    孤荷凌寒自学python第六十六天学习mongoDB的基本操作并进行简单封装5并学习权限设置 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十二天. 今天继续学习mongo ...

  3. 孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4

    孤荷凌寒自学python第六十五天学习mongoDB的基本操作并进行简单封装4 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十一天. 今天继续学习mongoDB的简单操作 ...

  4. 孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3

    孤荷凌寒自学python第六十四天学习mongoDB的基本操作并进行简单封装3 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第十天. 今天继续学习mongoDB的简单操作, ...

  5. 孤荷凌寒自学python第六十天在windows10上搭建本地Mongodb数据服务

     孤荷凌寒自学python第六十天在windows10上找搭建本地Mongodb数据服务 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第六天.成功在本地搭建了windows ...

  6. python第六十六天--sqlalchemy

    #!usr/bin/env python #-*-coding:utf-8-*- # Author calmyan #python #2017/7/6 21:29 #__author__='Admin ...

  7. python练习六十二:文件处理,往文件中所有添加指定的前缀

    往文件中所有添加指定的前缀 方法一:open方法 f_r = open('text.txt') f_w = open('text_new.txt','w+') i = 0 while True: i ...

  8. python第六十五天--python操作mysql

    pymysql模块对mysql进行 import pymysql # 创建连接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='ro ...

  9. python练习六十九:urllib爬取练习

    爬取图片,将链接中的图片取出来,并统计一共下载了多少图片 代码: def fetch_pictures(url): headers = {'User-Agent':'Mozilla/5.0 (Wind ...

随机推荐

  1. ADSL 动态IP拨号VPS 软件配置

    http://yun.baidu.com/share/link?uk=2520566727&shareid=330788421&third=0&adapt=pc&fr= ...

  2. postgresql 表继承

    可以按如下语句创建表 CREATE TABLE capitals ( name text, population real, altitude int, -- (in ft) state ) ); C ...

  3. PyCharm的基本快捷键和配置简介

    快捷键 1.编辑(Editing)Ctrl + Space 基本的代码完成(类.方法.属性)Ctrl + Alt + Space 快速导入任意类Ctrl + Shift + Enter 语句完成Ctr ...

  4. nginx ngx_http_sub_module使用

    ngx_http_sub_module模块是一个过滤器,它修改网站响应内容中的字符串,比如你想把响应内容中的‘iuwai’全部替换成‘aaaaa‘,这个模块已经内置在nginx中,但是默认未安装,需要 ...

  5. Java并发编程笔记之Timer源码分析

    timer在JDK里面,是很早的一个API了.具有延时的,并具有周期性的任务,在newScheduledThreadPool出来之前我们一般会用Timer和TimerTask来做,但是Timer存在一 ...

  6. RPC的基础:调研EOS插件http_plugin

    区块链的应用是基于http服务,这种能力在EOS中是依靠http_plugin插件赋予的. 关键字:通讯模式,add_api,http server,https server,unix server, ...

  7. Struts2学习(四)———— ognl表达式、值栈、actionContext之间的关系

    一.什么是Ognl? 通过百度百科查询到的解释,其中详细的说明了OGNL的作用. 下面我们就对OGNL这5个作用进行讲解 1.存取对象的任意属性,简单说就是对javabean进行操作(重要) 2.调用 ...

  8. Docker系列之Docker容器(读书笔记)

    一.介绍 容器是独立运行的一个或一组应用,以及它们的运行态环境.对应的,虚拟机可以理解为模拟运行的一整套操作系统和排在上面的应用. 二.容器 2.1 启动容器 启动容器有两种方式,一种是基于镜像新建一 ...

  9. 深入理解Java重载与重写

    我们都知道Java有三大宝,分别是:多态.封装.继承.其中多态主要体现就是重写与重载(有些人认为重载根本不属于多态)两种方式,那么今天就结合研读过JVM之后自己的理解来聊聊重载与重写的VM内部是怎么实 ...

  10. C++多重继承的构造执行顺序

    一个类,它可能有基类,也可能存在多个基类,这些类里面还可能是虚拟基类,并且在类的本身也可能存在对象成员.那么所涉及的这些类或对象成员会以什么样的顺序来调用它们各自的构造函数呢?今天我们就来举例分析下. ...