예제 #1
0
 def __init__(self, app=None, queue=None):
     self.app = app
     self.queue = queue
     self.config = self.app.config
     if not (self.config.get('RPC_USER_NAME')
             and self.config.get('RPC_PASSWORD')
             and self.config.get('RPC_HOST')):
         logger.error('没有配置rpc服务器的用户名和密码')
         raise Exception
     self.credentials = pika.PlainCredentials(self.config['RPC_USER_NAME'],
                                              self.config['RPC_PASSWORD'])
     self._connection = pika.BlockingConnection(
         pika.ConnectionParameters(self.config['RPC_HOST'],
                                   credentials=self.credentials))
     self._channel = self._connection.channel()
     self._rpc_class_list = []
예제 #2
0
    def send_sync(self, body, exchange, key, timeout=5):
        """
        发送并同步接受回复消息
        :return:
        """
        callback_queue = self.declare_queue(exclusive=True,
                                            auto_delete=True)  # 得到随机回调队列名
        self._channel.basic_consume(
            self.on_response,  # 客户端消费回调队列
            no_ack=True,
            queue=callback_queue)

        corr_id = str(uuid.uuid4())  # 生成客户端请求id
        self.data[corr_id] = {
            'isAccept': False,
            'result': None,
            'callbackQueue': callback_queue
        }
        self._channel.basic_publish(  # 发送数据给服务端
            exchange=exchange,
            routing_key=key,
            body=body,
            properties=pika.BasicProperties(
                reply_to=callback_queue,
                correlation_id=corr_id,
            ))

        end = time.time() + timeout
        while time.time() < end:
            if self.data[corr_id]['isAccept']:  # 判断是否接收到服务端返回的消息
                logger.info("Got the RPC server response => {}".format(
                    self.data[corr_id]['result']))
                return self.data[corr_id]['result']
            else:
                time.sleep(0.3)
                continue
        # 超时处理
        logger.error("Get the response timeout.")
        return None
예제 #3
0
    def send_sync(self, body, key=None, timeout=5):
        if not key:
            raise Exception("The routing key is not present.")
        corr_id = str(uuid.uuid4())  # generate correlation id
        callback_queue = self.temporary_queue_declare()  # 得到随机回调队列名
        self.data[corr_id] = {
            'isAccept': False,
            'result': None,
            'reply_queue_name': callback_queue
        }
        # Client consume reply_queue
        # self._channel.basic_consume(self.on_response,
        #                             no_ack=True,
        #                             queue=callback_queue)
        # update for python3.6 basic_consumer args order
        self._channel.basic_consume(callback_queue, self.on_response, no_ack=True)
        # send message to queue that server is consuming
        self._channel.basic_publish(
            exchange='',
            routing_key=key,
            body=body,
            properties=pika.BasicProperties(
                reply_to=callback_queue,
                correlation_id=corr_id,
            )
        )

        end = time.time() + timeout
        while time.time() < end:
            if self.data[corr_id]['isAccept']:  # 判断是否接收到服务端返回的消息
                logger.info("Got the RPC server response => {}".format(self.data[corr_id]['result']))
                return self.data[corr_id]['result']
            else:
                self._connection.process_data_events()
                time.sleep(0.3)
                continue
        # 超时处理
        logger.error("Get the response timeout.")
        return None