作业需求:
1、可以异步执行多个命令
2、对多台机器
完成情况:
实现了异步执行多个命令;通过在服务器端睡眠10s 模拟命令执行时间过长,进行异步操作,一次操作启动一次保护线程,主线程关闭,所有保护线程自动关闭
没做多台机器,没有这么多设备测试,虚拟机的linux python配置又一直没弄好,蛋疼。。。。
client.py
'''
Created on 2018年7月5日
@author: hcl
'''
import pika
import uuid
import threading
class Rpcclient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost'))#建立一个阻塞连接
self.channel = self.connection.channel()#在连接的基础上建立一个频道
result = self.channel.queue_declare(exclusive = True)#不指定queue名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
self.callback_queue = result.method.queue #给频道自动分配一个队列名
#设置从哪个queue接收消息,
#处理消息的函数on_response,是否需要确认消息
#默认情况下是要对消息进行确认的,以防止消息的丢失
self.channel.basic_consume(self.on_response,
no_ack=True,
queue=self.callback_queue)
self.task_id = []
def on_response(self,ch,method,props,body):
if self.corr_id == props.correlation_id:
self.response = body.decode()
def call(self,cmd):
#初始化response和corr_id属性
self.response = None
self.corr_id = str(uuid.uuid4())
#使用默认exchange向server种定义的rpc_queue发送消息
#在properties种指定replay_to属性和correlation_id属性用于告知远程server
#correlation_id属性用于匹配request和response
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to=self.callback_queue,
correlation_id=self.corr_id),
body = cmd)