【python】-- RabbitMQ RPC模型
RabbitMQ RPC模型
RPC(remote procedure call)模型说通俗一点就是客户端发一个请求给远程服务端,让它去执行,然后服务端端再把执行的结果再返回给客户端。

1、服务端
import pika #创建socket实例,声明管道,声明queue
connection = pika.BlockingConnection(pika.ConnectionParameters(host="localhost"))
channel = connection.channel()
channel.queue_declare(queue="rpc_queue") def fib(n):
"""
斐波那契数列
:param n:
:return:
"""
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): # props 是客户端发过来的消息
n = int(body)
print("fib(%s)" % n)
response = fib(n)
# 发布消息
ch.basic_publish(exchange="",
routing_key=props.reply_to, # props.reply_to从客户端取出双方约定好存放返回结果的queue
properties=pika.BasicProperties # 定义一些基本属性
(correlation_id=props.correlation_id), # props.correlation_id 从客户端取出当前请求的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("Awaiting RPC requests")
channel.start_consuming()
2、客户端
import pika
import uuid
import time class FibonacciRpcClient(object):
"""
斐波那契数列rpc客户端
""" def __init__(self):
"""
定义好创建socket实例、声明管道、声明随机产生的唯一queue、消费信息的静态变量
"""
self.connection = pika.BlockingConnection(pika.ConnectionParameters
(host="localhost"))
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):
print("---->", method, props)
# 当服务端返回的id跟当初请求的id一致时,再去读取服务端发送的信息保持数据的一致性
if self.corr_id == props.correlation_id: # 当服务端返回的id跟当初请求的id一致时,保持数据的一致性
self.response = body def call(self,n):
self.response = None
self.corr_id = str(uuid.uuid4())
self.channel.publish(exchange="",
routing_key="rpc_queue", # 双方的request所用的queue
properties=pika.BasicProperties( # 定义基本属性
reply_to=self.callback_queue, # 定义客户端服务端双方response的所用的Q
correlation_id=self.corr_id), # 定义这次request的唯一ID
body=str(n))
while self.response is None:
self.connection.process_data_events() # 非 阻塞版的start_consumer()
print("no msg....")
time.sleep(0.5)
return int(self.response) if __name__ == "__main__":
fibonacci_rpc = FibonacciRpcClient()
print("Requesting fib(8)")
response = fibonacci_rpc.call(8)
print("Got %r" % response)
3、输出
服务端:
Awaiting RPC requests
fib(8)
客户端:
Requesting fib(8)
no msg....
----> <Basic.Deliver(['consumer_tag=ctag1.cf2e7983c7d840db8c68f4571472c18d', 'delivery_tag=1', 'exchange=', 'redelivered=False', 'routing_key=amq.gen-ezXgs0tRO5SldZeRH97VPw'])> <BasicProperties(['correlation_id=601e860d-c93d-4c94-959a-3a39be177f7c'])>
no msg....
Got 21
【python】-- RabbitMQ RPC模型的更多相关文章
- Python RabbitMQ RPC实现
远程调用方法:R(remote) P(procedure) C(call) 为了说明如何使用RPC服务,我们将创建一个简单的客户端类. 它将公开一个名为call的方法,它发送一个RPC请求和块,直 ...
- Python之路-python(rabbitmq、redis)
一.RabbitMQ队列 安装python rabbitMQ module pip install pika or easy_install pika or 源码 https://pypi.pytho ...
- python RabbitMQ队列/redis
RabbitMQ队列 rabbitMQ是消息队列:想想之前的我们学过队列queue:threading queue(线程queue,多个线程之间进行数据交互).进程queue(父进程与子进程进行交互或 ...
- 认识RabbitMQ交换机模型
前言 RabbitMQ是消息队列中间件(Message Queue Middleware)中一种,工作虽然有用到,但是却没有形成很好的整体包括,主要是一些基础概念的认识,这里通过阅读<Rabbi ...
- Spring - 几种RPC模型的使用与比较
Spring中,用JMS搞RPC时会用到: org.springframework.jms.remoting.JmsInvokerServiceExporter org.springframework ...
- python RabbitMQ队列使用(入门篇)
---恢复内容开始--- python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种que ...
- Python RabbitMQ消息队列
python内的队列queue 线程 queue:不同线程交互,不能夸进程 进程 queue:只能用于父进程与子进程,或者同一父进程下的多个子进程,进行交互 注:不同的两个独立进程是不能交互的. ...
- python调用rpc实现分布式系统
rpc 一般俗称,远程过程调用,把本地的函数,放到远端去调用. 通常我们调用一个方法,譬如: sumadd(10, 20),sumadd方法的具体实现要么是用户自己定义,要么存在于该语言的库函数中,也 ...
- python RabbitMQ队列使用
python RabbitMQ队列使用 关于python的queue介绍 关于python的队列,内置的有两种,一种是线程queue,另一种是进程queue,但是这两种queue都是只能在同一个进程下 ...
随机推荐
- windows 10 超级优化提速 附系统服务列表纯净
如图,本机安装了vs2017 office2016 迅雷.谷歌浏览器,不建议安装其它任何软件.vs2017为开发软件,用于编程,一般用户用不到. 如果想安装其它的软件,建议优先使用绿色版本的. 下载服 ...
- axis2 利用小工具cat.aar
Axis2: Web Service是现在最适合实现SOAP的技术,而Axis2是实现Web Service的一种技术框架(架构). 昨天把把菜刀脚本打包发现<>在xml会被转义,导致菜刀 ...
- python 类特殊成员
class Foo: def __init__(self,age): self.age=age print('init') def __call__(self): print('call') def ...
- urllib urllib2
#-*-coding:utf-8-*- import urllib import urllib2 import cookielib ##urllib url="http://www.qq.c ...
- ionic准备之angular基础——继承(3)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- sqlserver 中EXEC和sp_executesql使用介绍
sqlserver 中EXEC和sp_executesql使用介绍 MSSQL为我们提供了两种动态运行SQL语句的命令,各自是EXEC和sp_executesql;通常,sp_executesql则更 ...
- 谈谈WEB开发中的苦大难字符集问题
http://www.lanceyan.com/tech/arch/web_luanma.html记得刚做javaweb开发的时候被这个编码问题搞得晕头转向,经常稀里糊涂的编码正常了一会编码又乱了.那 ...
- session的两个小案例
学完了session,写两个小案例加深一下对session的巩固. 1. 用户登陆案例 登陆html页面提交后,将参数带给处理登陆的servlet,该servlet将获得登陆的用户名和密码,并将这些信 ...
- dispatch_after中时间的计算
dispatch_after中用的时间是纳秒,所以需要进行转换:desDelayInSeconds(目标时间,比如2s)* NSEC_PER_SEC double delayInSeconds = 0 ...
- const readonly
静态常量(compile-time constants)静态常量是指编译器在编译时候会对常量进行解析,并将常量的值替换成初始化的那个值. 动态常量(runtime constants)而动态常量的值则 ...