更多详情参考官方文档:https://www.rabbitmq.com/tutorials/tutorial-six-python.html

参考博客:https://blog.csdn.net/weixin_41896508/article/details/80997828

微服务通信RPC

01-HelloWorld(简单的消息队列)

  send.py  

import pika
#与RabbitMQ服务器建立连接
credential = pika.PlainCredentials('yang','abc123456')#erase_on_connect是否清楚凭证
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost',credentials=credential))
#创建频道
channel = connection.channel()#channel_number参数指定频道编号,建议默认pika自行管理
#创建频道传递消息的队列
channel.queue_declare(queue='hello') #向频道队列中发送消息
channel.basic_publish(exchange='',
routing_key='hello',
body='hello world!') print('[x]消息发送成功!')
connection.close()#断开连接

send.py

  receive.py

import pika
credentials = pika.PlainCredentials('yang','abc123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1',port=5672,credentials=credentials))
channel = connection.channel()
channel.queue_declare(queue='hello') def callback(ch, method, properties, body):
print(f'{body.decode()}') channel.basic_consume(queue='hello',
auto_ack=True,#开启自动确认关闭手动确认
on_message_callback=callback) print(' [*] Waiting for messages. ')
channel.start_consuming()

recieve.py

02-WorkQueues(任务队列)

  new_task.py  

'''
任务生产者将任务发送到指定队列中,多个工作者进行均分协同处理(启多个工作者)
'''
import pika
credentials = pika.PlainCredentials('yang','abc123456')
connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1',5672,credentials=credentials))
channel = connection.channel() channel.queue_declare(queue='work_queue',durable=True)#durable=True指定消息持久化,出现异常不会丢失。注意basic_publish需要设置参数 for i in range(1000):
message = f'new_task{i}...'
channel.basic_publish(
exchange='',
routing_key='work_queue',
body=message,
properties = pika.BasicProperties(delivery_mode=2, )# 支持数据持久化:2代表消息是持久
)
print(f'Send>>>{message}') connection.close()

new_task.py

  worker.py

import time
import random
import pika
credentials = pika.PlainCredentials('yang','abc123456')
connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1',5672,credentials=credentials))
channel = connection.channel() channel.queue_declare(queue='work_queue',durable=True)#durable=True指定消息持久化,出现异常不会丢失 def callback(ch, method, properties, body):
print(f'Rceive>>{body}')
time.sleep(random.random())
print(f'Done--{body.decode()}')
# 手动确认机制(在消费者挂掉没有给确认时,消息不会丢失)
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1)#此设置确保在没有进行确认之前当前接受得任务只有1个(不设置默认是平均分配)
channel.basic_consume(
queue='work_queue',
on_message_callback=callback
) channel.start_consuming()

worker.py

03-PublishSubcribe(订阅发布)

  publish.py 

'''
发布者发布一条任务,通过交换机发送到与此交换机简历连接的所有队列中进行共享(启多个订阅者)
'''
import pika
credentials = pika.PlainCredentials('yang','abc123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', port=5672, credentials=credentials)) channel = connection.channel() #创建频道的交换器(交换器负责将任务发送到连接词交换器的所有的队列中)
channel.exchange_declare(exchange='logs',
exchange_type='fanout',#创建一个fanout(广播)类型的交换机exchange,名字为logs
durable=True)#durabl持久化 for i in range(1000):
message = f'new_task{i}...'
channel.basic_publish(
exchange='logs',#指定交换机
routing_key='',#无需指定路由键队列,由交换机进行发送
body=message,
properties = pika.BasicProperties(delivery_mode=2, )# delivery_mode支持数据持久化:2代表消息是持久
)
print(f'Send>>>{message}') connection.close()

publish.py

  subcribe.py

import pika
credentials = pika.PlainCredentials('yang','abc123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1', port=5672, credentials=credentials)) channel = connection.channel() #与交换器建立连接
channel.exchange_declare(exchange='logs',exchange_type='fanout',durable=True)#durable持久化 #确定消息队列(不指定队列名,每个订阅者rabbirmq服务器连接都会创建一个随机队列)
result= channel.queue_declare(queue='',exclusive=True,durable=True)#exclusive=True当断开连接时,队列销毁(持久化没有用,设置了断开销毁)
queue_name= result.method.queue
#与交换机新建的的随机队列进行绑定
channel.queue_bind(exchange='logs',queue=queue_name) def callback(ch, method, properties, body):
print(f'Rceive>>{body}')
print(f'Done--{body.decode()}')
# 手动确认机制(在消费者挂掉没有给确认时,消息不会丢失)
ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_consume(
queue=queue_name,
on_message_callback=callback
) channel.start_consuming()

subcribe.py

06-RPC(远程过程调用)

  rpc_client.py

import pika
import uuid class RpcClient(object):
def __init__(self):
credentials = pika.PlainCredentials('yang', 'abc123456')
self.connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1', 5672, credentials=credentials)) self.channel = self.connection.channel() # 随机创建一个唯一队列
result = self.channel.queue_declare(queue='', exclusive=True)
self.callback_queue = result.method.queue # 接收回调队列中的消息
self.channel.basic_consume(
queue=self.callback_queue,
on_message_callback=self.on_response,
auto_ack=True) def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
self.response = body def call(self, m, n):
self.response = None
self.corr_id = str(uuid.uuid4())
# 想通信队列放入消息
self.channel.basic_publish(
exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
delivery_mode=2,#持久化参数
# content_type='application/json',#指定body数据类型,不指定则为字符串(有待测试)
reply_to=self.callback_queue, # 指定回调队列
correlation_id=self.corr_id, # 指定本次请求标识id
),
body=str(m) + ',' + str(n)
) while self.response is None:
self.connection.process_data_events()
return int(self.response) clinet_rpc = RpcClient() print(" [x] Requesting add(30,30)")
response = clinet_rpc.call(30,20)
print(" [.] Got %r" % response)

rpc_client.py

  rpc_server.py

import pika

credentials = pika.PlainCredentials('yang', 'abc123456')
connection = pika.BlockingConnection(pika.ConnectionParameters('127.0.0.1', 5672, credentials=credentials))
channel = connection.channel() channel.queue_declare(queue='rpc_queue', durable=True) # durable=True消息持久化 def add(m, n):
return m + n def on_request(ch, method, props, body):
m, n = body.decode().split(',')
response = add(int(m), int(n)) #将响应信息放入指定的回调队列中
channel.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(
queue='rpc_queue',
on_message_callback=on_request,
) print('Awaiting RPC requests...')
channel.start_consuming()

rpc_server.py  

RabbitMQ应用示例的更多相关文章

  1. NET下RabbitMQ实践[示例篇]

    在上一篇文章中,介绍了在window环境下安装erlang,rabbitmq-server,以免配置用户,权限,虚拟机等内容.         今天将会介绍如果使用rabbitmq进行简单的消息入队, ...

  2. RabbitMQ基本示例,轮询机制,no_ack作用

    一.RabbitMQ简介: ''' RabbitMQ就是消息队列 之前不是学了Queue了吗,都是队列还学RabbitMQ干嘛? 干的事情是一样的 Python的Queue有两个, 一个线程Queue ...

  3. AMQP消息队列之RabbitMQ简单示例

    前面一篇文章讲了如何快速搭建一个ActiveMQ的示例程序,ActiveMQ是JMS的实现,那这篇文章就再看下另外一种消息队列AMQP的代表实现RabbitMQ的简单示例吧.在具体讲解之前,先通过一个 ...

  4. laravel框架的rabbitmq使用示例[多队列封装]

    RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件).RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的.所有主要 ...

  5. rabbitmq 简单示例(Hello World)

    一:消息中间件: AMQP,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计 RabbitMQ是实现AMQP( ...

  6. Spring Boot + RabbitMQ 使用示例

    基础知识 虚拟主机 (Virtual Host): 每个 virtual host 拥有自己的 exchanges, queues 等 (类似 MySQL 中的库) 交换器 (Exchange): 生 ...

  7. RabbitMQ基础组件和SpringBoot整合RabbitMQ简单示例

    交换器(Exchange) 交换器就像路由器,我们先是把消息发到交换器,然后交换器再根据绑定键(binding key)和生产者发送消息时的路由键routingKey, 按照交换类型Exchange ...

  8. springboot + rabbitmq 整合示例

    几个概念说明:Broker:简单来说就是消息队列服务器实体.Exchange:消息交换机,它指定消息按什么规则,路由到哪个队列.Queue:消息队列载体,每个消息都会被投入到一个或多个队列.Bindi ...

  9. 【rabbitmq】rabbitmq概念解析--消息确认--示例程序

    概述 本示例程序全部来自rabbitmq官方示例程序,rabbitmq-demo: 官方共有6个demo,针对不同的语言(如 C#,Java,Spring-AMQP等),都有不同的示例程序: 本示例程 ...

随机推荐

  1. 我做了一个 HTML 可视化编辑工具,有前途吗?

    疫情在家的这段时间,我做了一个 HTML 可视化编辑工具,做的时候信心满满,差不多完成了,现在反而不如以前信心足了,这玩意有用吗?代码地址: https://github.com/vularsoft/ ...

  2. 鸟哥Linux私房菜(基础篇)——第五章:首次登入与在线求助 man page笔记

    1.X Winsows与文本模式的切换 ●[Ctrl] + [Alt] + [F1] ~ [F6] :文字接口登入 tty1 ~ tty6 终端机.        ●[Ctrl] + [Alt] + ...

  3. java 之 学习过程中遇到的大佬博客

    大佬1号:zejian 博客:https://blog.csdn.net/javazejian

  4. nodeJS中express框架设置全局跨域请求头

    //设置跨域请求头 router.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin&qu ...

  5. Hadoop学习笔记(三) ——HDFS

    参考书籍:<Hadoop实战>第二版 第9章:HDFS详解 1. HDFS基本操作 @ 出现的bug信息 @-@ WARN util.NativeCodeLoader: Unable to ...

  6. Codeforces Round #590

    题目链接:Round #590 题目答案:官方Editorial.My Solution A. Equalize Prices Again 签到题还WA了一发,向上取整有点问题: //my wrong ...

  7. C++ 模板(template) 的定义

    定义: 模板(template)是实现代码重用机制的一种工具,它可以实现类型参数化,把类型定义为参数(模板元编程),从而实现了真正的代码可重用性. 模板是用来批量生成功能和形式都几乎相同的代码的.编译 ...

  8. YUM 安装lnmy

    yum -y install nginx systemctl start nginx.service yum -y install php php-fpm php-mysql php-gd libjp ...

  9. VMware15.5.0安装MacOS10.15.0系统 安装步骤(上)

    VMware15.5.0安装MacOS10.15.0系统安装步骤(上)超详细! 说明: 本文是目前最新的安装和调配教程且MacOS10.15和10.16版本搭建方法相同,我也会在一些细节地方加上小技巧 ...

  10. zabbix日常问题总结

    1.connection to database 'zabbix' failed: [1040] Too many connections 问题:数据库连接池太少解决:增加数据库连接池步骤:(1).进 ...