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 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题