duanlei4759 2017-05-22 12:08
浏览 442
已采纳

gRPC:如何使用Go服务器在Java客户端中获取多个返回值

I have a protocol buffer file:

syntax = "proto3";
package v1api;
option java_multiple_files = true;
option java_package = "myApp.v1";
option java_outer_classname = "V1";

service API {
    rpc Login(LoginRequest) returns (LoginResponse)
}

message LoginRequest {
    int pin = 1
}

message LoginResponse {
    string token = 1
}

I have my server written in Go (a language that can return multiple values), and my client being an Android application.

When I use this protoBuf to generate Go code for server, it is something like:

...
func (c *aPIClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) {
    out := new(LoginResponse)
    err := grpc.Invoke(ctx, "/v1api.API/Login", in, out, c.cc, opts...)
    if err != nil {
        return nil, err
    }
    return out, nil
}
...

Notice that there are two return values, (*LoginResponse, error).

Now, when I use this protoBuf to generate Java code for my Android side, I get something like:

public myApp.v1.LoginResponse login(myApp.v1.LoginRequest request) {
    return blockingUnaryCall(getChannel(), METHOD_LOGIN, getCallOptions(), request);
}

Notice that, here, there is just one return value like Java allows, myApp.v1.LoginResponse.

My question is, in case of an error returned by the server (something like: return nil, err), how will I get that second return value in my Android side.

  • 写回答

2条回答 默认 最新

  • dongma2388 2017-05-22 19:57
    关注

    In Go, the error returned by your Login method will get converted into the wire format status code and message used by gRPC. In your case, if you return a status.Status, the Code and message will be sent and show up on the Java side as a StatusRuntimeException. If you return a non Status error, gRPC will convert it to the UNKNOWN code, but preserve the message.

    This is the reason there are two return values for Go, vs. just one for Java. Java can "return" a secondary value by throwing an exception in its place.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵