猿问

如何在 gRPC 调用中直接传递原始二进制文件?

我已经有了 protobuf 消息对象的 proto 二进制文件。

现在要进行 gRPC 调用,我需要解组它并将消息对象发送到 gRPC 客户端(它将再次编组相同的对象),在此过程中浪费延迟。

如何通过将二进制文件传递给客户端来避免这种情况?


慕仙森
浏览 173回答 2
2回答

慕的地10843

这可以使用自定义编解码器来实现。自定义编解码器可以定义为type StubbedCodec struct{}func (cb StubbedCodec) Marshal(v interface{}) ([]byte, error) {    return v.([]byte), nil}func (cb StubbedCodec) Unmarshal(data []byte, v interface{}) error {    ba, _ := v.([]byte)    for index, byte := range data {        ba[index] = byte    }    return nil}一旦我们有了这个,我们可以将编解码器作为拨号选项传递为grpc.Dial(grpcServer, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithDefaultCallOptions(grpc.ForceCodec(StubbedCodec{})))这将强制 grpc 使用您的编解码器,它基本上什么都不做(如上定义)。

慕娘9325324

如果要发送原始二进制数据,请使用 protobuf 类型,bytes例如// .proto filemessage MyRawData {  bytes rawbin = 1;}这将转换go为字节片,非常适合存储原始二进制文件:// go-codetype MyRawData struct {       Rawbin []byte   `protobuf:"bytes,1,opt,name=rawbin,proto3" json:"rawbin,omitempty"`}
随时随地看视频慕课网APP

相关分类

Go
我要回答