【基于RabbitMQ rpc实现的主机管理】

要求:〖Demo〗-- 基于RabbitMQ rpc实现的主机管理

 

文件分布:

〖Demo〗-- 基于RabbitMQ rpc实现的主机管理

流程图:

〖Demo〗-- 基于RabbitMQ rpc实现的主机管理

import pika
import os
import socket

class Server(object):
    def __init__(self, queuename):
        self.queuename = queuename
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost'))
        self.channel = self.connection.channel()  #声明一个管道
        self.channel.queue_declare(queue=self.queuename)
    def handle(self,command):
        message = os.popen(command.decode()).read()
        if not message:
            message = 'wrong command'
        return message
    def on_requet(self, ch, method,props,body):
        response = self.handle(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)#确保任务完成

    def start(self):
        self.channel.basic_consume(self.on_requet, queue=self.queuename) #收到消息就调用on_requet
        print(" [x] Awaiting RPC requests")
        self.channel.start_consuming()





if __name__ == "__main__":
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname) # 获取本地ip地址作为queue name
    print(ip)
    queue_name = ip
    server = Server(queue_name)
    server.start()
server

相关文章:

  • 2022-12-23
  • 2020-04-21
  • 2018-12-12
  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
  • 2021-09-07
  • 2021-09-25
猜你喜欢
  • 2022-12-23
  • 2021-09-15
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2021-11-25
相关资源
相似解决方案