示例#1
0
    def test(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
        """
        _check_result = CResult()
        if self._channel is None:
            # 没有连接
            _check_result.status = msg_pb2.HealthResponse.UNKNOWN
        elif self._test_use_health_check:
            # 使用标准健康检查
            self._health_stub = SimpleGRpcTools.generate_health_check_stub(
                self._channel)
            _check_result = SimpleGRpcTools.health_check_by_stub(
                self._health_stub, self._servicer_name, timeout=self._timeout)
        else:
            # 使用自定义的健康检查
            _check_result = SimpleGRpcTools.simple_grpc_health_check_by_stub(
                self._stub, timeout=self._timeout)
        # 返回结果
        return _check_result
示例#2
0
    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