PythonRabbitMQ消息队列实现rpc-创新互联
上个项目中用到了ActiveMQ,只是简单应用,安装完成后直接是用就可以了。由于新项目中一些硬件的限制,需要把消息队列换成RabbitMQ。

RabbitMQ中的几种模式和机制比ActiveMQ多多了,根据业务需要,使用RPC实现功能,其中踩过的一些坑,有必要记录一下了。
上代码,目录结构分为 c_server、c_client、c_hanlder:
c_server:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pika
import time
import json
import io
import yaml
s_exchange = input("请输入交换机名称->>").decode('utf-8').strip()
s_queue = input("输入消息队列名称->>").decode('utf-8').strip()
credentials = pika.PlainCredentials('system', 'manager')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='XXX.XXX.XXX.XXX',credentials=credentials))
# 定义
channel = connection.channel()
channel.exchange_declare(exchange=s_exchange, exchange_type='direct')
channel.queue_declare(queue=s_queue, exclusive=True)
channel.queue_bind(queue=s_queue, exchange=s_exchange)
def s_manage(content):
# 解决unicode转码问题 json.JSONDecoder().decode(content)
str_content = yaml.safe_load(json.loads(content,encoding='utf-8'))
str_res = {
"errorid": 0,
"resp": str_content['cmd'],
"errorcont": "成功"
}
return json.dumps(str_res)
def on_request(ch, method, props, body):
response = s_manage(body)
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id = \
props.correlation_id),
body=response)
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request, queue=s_queue)
print(" [x] Awaiting RPC requests")
channel.start_consuming() 本文题目:PythonRabbitMQ消息队列实现rpc-创新互联
文章分享:http://www.scyingshan.cn/article/dhcgcj.html


咨询
建站咨询
