
我是 GRPC 新手,无法解决一个问题。当应用程序已经运行时是否可以创建 protobuff 文件?
例如,我从用户那里收到一个 json ,如下所示:
"protobuf_file": "protobuf.proto", // File will be also recieved from user "service_name": "Unary", "method_name": "GetServerResponse", "request_data_serializer_name": "MessageRequest", "body": "grpc_request_data.json", // File will be also recieved from user
这里我有一个 .proto 文件、服务名称、方法和消息,以及另一个带有数据的 json 来填充消息。
现在我必须打开连接并使用提供的数据调用所需的方法。
TY!
附注.proto 文件(来自获取说明指南)将是:
syntax = "proto3";
package protobuf_all_modes;
service Unary {
rpc GetServerResponse(MessageRequest) returns (MessageResponse) {}
}
message MessageRequest {
string message = 1;
}
message MessageResponse {
string message = 1;
int32 random_int32 = 2;
}第二个 json 将是:
{
"message": "hello World!"
}我不知道要寻找解决方案。如有任何建议,将不胜感激
如果有人遇到同样的问题,有一个非常好的库 - https://pkg.go.dev/github.com/jhump/[email protected]/dynamic 和一个子包https://pkg.go.dev/github。 com/jhump/[电子邮件受保护]/dynamic/grpcdynamic
代码片段将是:
parser
func NewGrpcObject(operation *BaseOperation) *GrpcObject {
fns, err := protoparse.ResolveFilenames([]string{"./"}, operation.ProtoFile) // prase .proto file
if err != nil {
log.Error(err)
}
parser := protoparse.Parser{}
fds, err := parser.ParseFiles(fns...)
if err != nil {
log.Error(err)
}
descriptor := fds[0] // In my case there will be only one .proto
pkg := descriptor.GetPackage()
serviceDescriptor := descriptor.FindService(pkg + "." + operation.ServiceName) // name of service descriptor will be with package name first
methodDescriptor := serviceDescriptor.FindMethodByName(operation.MethodName)
requestDescriptor := methodDescriptor.GetInputType() // You can get types for request and response
responseDescriptor := methodDescriptor.GetOutputType()
return &GrpcObject{
RequestDesc: requestDescriptor,
MethodDesc: methodDescriptor,
ResponseDesc: responseDescriptor,
}
}caller
// connect
conn, _ := grpc.Dial(operation.Host, grpc.WithTransportCredentials(credentials.NewTLS(c.TLSClientConfig.NewTLSConfig())))
stub = grpcdynamic.NewStub(conn)
// call
message := dynamic.NewMessage(operation.GrpcObject.RequestDesc) // from parser
message.UnmarshalJSON(operation.Body) // here a JSON to fill message
resp, err := stub.InvokeRpc(ctx, operation.GrpcObject.MethodDesc, message)
if err != nil {
// handle err
}
respMessage := dynamic.NewMessage(operation.GrpcObject.ResponseDesc) // descriptor from parser
respMessage.ConvertFrom(resp) // convert message from raw response以上就是GO 和 GRPC:“在飞行中”创建 protobuff 类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号