def __init__(self, connect_para): """ 构造函数 @param {NullObj} connect_para - 具体参数见SimpleGRpcConnection.generate_connect_para函数的定义 @throws {ConnectionError} - 如果连接时需要检查有效性,当检查失败时抛出该异常 """ # 内部变量初始化 self._trace_info_dict = dict() # 初始化参数 self._connect_para = connect_para self._fill_connect_para(self._connect_para) self._test_on_connect = connect_para.test_on_connect self._test_use_health_check = connect_para.test_use_health_check self._servicer_name = connect_para.servicer_name self._logger = connect_para.logger self._log_level = connect_para.log_level self._timeout = connect_para.timeout # 日志处理 if self._logger is None and connect_para.is_use_global_logger: # 使用全局logger self._logger = RunTool.get_global_logger() # 进行连接 self._channel = SimpleGRpcTools.generate_channel(self._connect_para) self._stub = SimpleGRpcTools.generate_call_stub(self._channel) # 检查连接有效性 if self._test_on_connect: _check_result = self.test() if _check_result.status != msg_pb2.HealthResponse.SERVING: # 连接失败,打印日志后抛出异常 if self._logger is not None: self._logger.log( self._log_level, '[EX:%s]%s%s\n%s' % (_check_result.error, 'SimpleGRpcConnection init error: ', _check_result.msg, _check_result.trace_str)) raise ConnectionError(_check_result.msg)
def reconnect(self): """ 重新连接 @returns {CResult} - 响应对象,判断成功的方法: ret.status == msg_pb2.HealthResponse.SERVING 总共有以下几种状态 health_pb2.HealthResponse.UNKNOWN health_pb2.HealthResponse.SERVICE_UNKNOWN health_pb2.HealthResponse.NOT_SERVING health_pb2.HealthResponse.SERVING """ # 先关闭连接 self.close() # 进行连接 self._channel = SimpleGRpcTools.generate_channel(self._connect_para) self._stub = SimpleGRpcTools.generate_call_stub(self._channel) # 检查连接有效性 if self._test_on_connect: _check_result = self.test() if not _check_result.is_success( ) or _check_result.status != msg_pb2.HealthResponse.SERVING: # 连接失败,打印日志后抛出异常 if self._logger is not None: self._logger.log( self._log_level, '[EX:%s]%s%s, service status:%s\n%s' % (_check_result.error, 'SimpleGRpcConnection reconnect error: ', _check_result.msg, _check_result.status, _check_result.trace_str)) return _check_result else: # 不检查的情况,直接返回成功,连接状态为SERVING _check_result = CResult('00000') _check_result.status = msg_pb2.HealthResponse.SERVING return _check_result