Python-RabbitMQ消息队列实现rpc
2024-08-30 00:48:38
客户端通过发送命令来调用服务端的某些服务,服务端把结果再返回给客户端
这样使得RabbitMQ的消息发送端和接收端都能发送消息
返回结果的时候需要指定另一个队列
服务器端
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR" import pika
import os connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1'))
channel = connection.channel() channel.queue_declare(queue='rpc_q') def cmd(n):
cmd_result = os.popen(n)
cmd_result = cmd_result.read()
return cmd_result def on_request(ch, method, props, body):
body = body.decode()
print('执行命令:', body)
response = cmd(body)
print(response) ch.basic_publish(exchange='',
routing_key=props.reply_to, # 把消息发送到用来返回消息的queue
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_q') print('等待请求')
channel.start_consuming()
客户端
# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR" import pika
import uuid
import time class RpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1')) self.channel = self.connection.channel() result = self.channel.queue_declare(exclusive=True)
self.callback_queue = result.method.queue # 生成随机的queue self.channel.basic_consume(self.on_response, # 一收到消息就调用op_response方法
no_ack=True,
queue=self.callback_queue,
) def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id: # 判断服务端发送的uuid和客户端发送的uuid是否匹配
self.response = body def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4())
self.channel.basic_publish(exchange='',
routing_key='rpc_q',
properties=pika.BasicProperties(
reply_to=self.callback_queue, # 把返回的消息发送到用来返回结果的queue
correlation_id=self.corr_id,
),
body=n,
)
while self.response is None:
self.connection.process_data_events() # 相当于非阻塞的start_consuming()
print('当前没有消息')
time.sleep(3)
return self.response while True:
cmd = input('>>>:').strip()
print('执行命令:', cmd)
rpc = RpcClient()
response = rpc.call(cmd)
print(response.decode())
开启一个客户端和一个服务端
执行结果:
服务器端
客户端
最新文章
- 让ztree树默认是关闭的
- java读取properties配置文件信息
- etc/profile和/etc/environment的比较
- HTTP会话原理解释与应用
- fedora23开发环境搭建手册
- elk工作原理
- VBS 批量修改多个文件夹下的文字命名
- bootstrap的alert提示框的关闭后再显示问题
- python抓取NBA现役球员基本信息数据
- 预防黑客入侵 防黑必学的cmd命令vs网络安全
- Qt4项目迁移到Qt5问题:greaterThan(QT_MAJOR_VERSION, 4): QT += widgets .
- 详解docker实战之搭建私有镜像仓库 - kurbernetes
- 自定义Wed框架
- 【Django】ModuleNotFoundError: No module named 'books_ordersschool'
- Jboss 数据源密码明文加密
- MyEclipse移动开发教程:设置所需配置的iOS应用(四)
- HDU6387 AraBellaC
- oracle 序列 视图 索引 同义词
- java_String、StringBuilder
- 在线sass编译器
热门文章
- activiti踩坑
- androidAndroid开发学习--Ionic+Cordova 环境搭建
- linux 如何查找命令的路径
- LeetCode:长度最小的子数组【209】
- shiro1
- 微信小程序消息模板
- 【leetcode刷题笔记】Jump Game
- android电池(四):电池 电量计(MAX17040)驱动分析篇【转】
- Delphi 函数的重载和作用域
- php执行外部命令函数:exec()、passthru()、system()、shell_exec()对比