1 Star 3 Fork 1

Paul / rabbitmq-python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
6-rpc-server.py 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
Paul 提交于 2021-07-04 13:04 . 提交RPC模式
# -*- encoding: utf-8 -*-
"""
@Time : 2021/6/12 23:43
@Author : boli.hong
RPC模式
"""
import pika
import sys
# 连接RabbitMQ服务器
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)
# 设置消费者允许的最大未确认消息数量为1
channel.basic_qos(prefetch_count=1)
# 定义队列的消费回调,将消息传递给回调函数同时关闭自动消息确认
channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)
print(" [x] Awaiting RPC requests")
# 开始消费/接收消息,注意:这是一个死循环,相当于`while True`
channel.start_consuming()
Python
1
https://gitee.com/paultest/rabbitmq-python.git
git@gitee.com:paultest/rabbitmq-python.git
paultest
rabbitmq-python
rabbitmq-python
master

搜索帮助