1

在向 GRPC-java 服务器发出请求后,在 Python 客户端中,我得到以下类型的对象:

<class 'GetInsertService_pb2.CountResponse'>

它有以下方法:

['ByteSize', 'Clear', 'ClearExtension', 'ClearField', 'CopyFrom', 'DESCRIPTOR', 'DiscardUnknownFields', 'Extensions', 'FindInitializationErrors', 'FromString', 'HasExtension', 'HasField', 'IsInitialized', 'ListFields', 'MergeFrom', 'MergeFromString', 'ParseFromString', 'RegisterExtension', 'SerializePartialToString', 'SerializeToString', 'SetInParent', 'UnknownFields', 'WhichOneof', '_CheckCalledFromGeneratedFile', '_SetListener', '__class__', '__deepcopy__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__unicode__', '_extensions_by_name', '_extensions_by_number', 'result']

原型看起来像这样:

message UIDRequest {
    string uid = 1;
}

//
message CountResponse {
    string result = 1;
}

service GetInsertService {
    rpc get(UIDRequest) returns (CountResponse);

}

我的java服务器实现:

public class GetInsertServiceImpl
    extends GetInsertServiceGrpc.GetInsertServiceImplBase {

  @Override
  public void get(
      GetInsertServiceOuterClass.UIDRequest request,
      StreamObserver<GetInsertServiceOuterClass.CountResponse> responseObserver) {

    RawKVClient dbClient = SingletonDB.getInstance().client;

    ByteString res =
        dbClient.get(ByteString.copyFrom(String.valueOf(request.getUid()), Charsets.UTF_8));
    GetInsertServiceOuterClass.CountResponse response =
        GetInsertServiceOuterClass.CountResponse.newBuilder()
            .setResult(res.toString())
            .build();
    // Use responseObserver to send a single response back
    responseObserver.onNext(response);

    // When you are done, you must call onCompleted.
    responseObserver.onCompleted();
  }

这是我的客户端 py 代码:

    channel_grpc = grpc.insecure_channel('ip:port')
    stub = GetInsertService_pb2_grpc.GetInsertServiceStub(channel_grpc)
    msg_count = stub.get(GetInsertService_pb2.UIDRequest(uid=user_id))

所以里面msg_count有一个值字符串result

但是当我这样做时:
-msg_count.SerializeToString()我得到b'\n\x1c<ByteString@3ffef3bb size=2>'
-msg_count.result返回result: "<ByteString@3ffef3bb size=2>"

如何获得实际值(如 '14' 而不是<ByteString@3ffef3bb size=2>)?

4

1 回答 1

-1

您的服务器可能会返回字符串<ByteString@3ffef3bb size=2>,而不是您的客户端代码。

同样来自您的评论,在 java 服务器中使用res.toStringUtf8()应用 utf8 编码。

于 2020-01-14T09:22:15.740 回答