客户端通过发送命令来调用服务端的某些服务,服务端把结果再返回给客户端

这样使得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())

开启一个客户端和一个服务端

执行结果:

服务器端

客户端

最新文章

  1. 让ztree树默认是关闭的
  2. java读取properties配置文件信息
  3. etc/profile和/etc/environment的比较
  4. HTTP会话原理解释与应用
  5. fedora23开发环境搭建手册
  6. elk工作原理
  7. VBS 批量修改多个文件夹下的文字命名
  8. bootstrap的alert提示框的关闭后再显示问题
  9. python抓取NBA现役球员基本信息数据
  10. 预防黑客入侵 防黑必学的cmd命令vs网络安全
  11. Qt4项目迁移到Qt5问题:greaterThan(QT_MAJOR_VERSION, 4): QT += widgets .
  12. 详解docker实战之搭建私有镜像仓库 - kurbernetes
  13. 自定义Wed框架
  14. 【Django】ModuleNotFoundError: No module named 'books_ordersschool'
  15. Jboss 数据源密码明文加密
  16. MyEclipse移动开发教程:设置所需配置的iOS应用(四)
  17. HDU6387 AraBellaC
  18. oracle 序列 视图 索引 同义词
  19. java_String、StringBuilder
  20. 在线sass编译器

热门文章

  1. activiti踩坑
  2. androidAndroid开发学习--Ionic+Cordova 环境搭建
  3. linux 如何查找命令的路径
  4. LeetCode:长度最小的子数组【209】
  5. shiro1
  6. 微信小程序消息模板
  7. 【leetcode刷题笔记】Jump Game
  8. android电池(四):电池 电量计(MAX17040)驱动分析篇【转】
  9. Delphi 函数的重载和作用域
  10. php执行外部命令函数:exec()、passthru()、system()、shell_exec()对比