zoukankan      html  css  js  c++  java
  • pibbtimq高级使用技术,双向通信

    本案例目是是服务端发送客户端,客户端收到反应给服务端,双向通信
    客户端代码如下:

    import pika
    import time

    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)
    e

    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)


    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(on_request, queue='rpc_queue')

    print(" [x] Awaiting RPC requests")
    channel.start_consuming()
    RPC
    client
    服务端代码:
    import pika
    import uuid


    class FibonacciRpcClient(object):
    def __init__(self):
    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):
    if self.corr_id == props.correlation_id:
    self.response = body

    def call(self, n):
    self.response = None
    self.corr_id = str(uuid.uuid4())
    self.channel.basic_publish(exchange='',
    routing_key='rpc_queue',
    properties=pika.BasicProperties(
    reply_to=self.callback_queue,
    correlation_id=self.corr_id,
    ),
    body=str(n))
    while self.response is None:
    self.connection.process_data_events()
    return int(self.response)


    fibonacci_rpc = FibonacciRpcClient()

    print(" [x] Requesting fib(30)")
    response = fibonacci_rpc.call(30)
    print(" [.] Got %r" % response)
    以上代整于老男孩14期自动 运维





  • 相关阅读:
    Nginx + FastCGI 程序(C/C++)搭建高性能web service的demo
    微服务架构
    异常点/离群点检测算法——LOF
    多边形区域填充算法--递归种子填充算法
    Java 关于容器集合等数据结构详情图解,一目了然
    平衡小车项目解读日志
    <LeetCode OJ> 101. Symmetric Tree
    【JVM】模板解释器--字节码的resolve过程
    hexo博客的相关配置
    【LeetCode】Find Minimum in Rotated Sorted Array 解题报告
  • 原文地址:https://www.cnblogs.com/fgxwan/p/9664653.html
Copyright © 2011-2022 走看看