本文介绍了如何发送在运行时确定格式的gRPC消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要对用Java做到这一点感兴趣,但是查看任何语言的解决方案都会有所帮助.

I'm primarily interested in doing this in Java, but seeing a solution in any language would be helpful.

根据各种文档,我正在阅读gRPC的默认工作流程是

According to various documentation that I'm reading the default workflow with gRPC is

  • 写一个.proto文件
  • 从该文件生成客户端和/或服务器代码
  • 编写程序并将其与生成的代码一起编译
  • Write a .proto file
  • Generate client and/or server code from that file
  • Write your program and compile it together with the generated code

我想做的是以编程方式(从.proto文件或通过其他方式)读取消息架构,然后将根据该架构布局的一些数据发送到某个地址.

What I want to do is programmaticaly read in a message schema (either from a .proto file or through some other means), and then send some data that's laid out according to that schema to some address.

我现在看到的唯一方法是外壳,在临时目录中生成代码,调用编译器,加载编译后的代码,并使用反射来获得预期的功能.

The only way I can see to do that right now is to shell out, generate code in a temp directory, invoke the compiler, load the compiled code, and use reflection to get at the intended functions.

对我来说,这听起来像是一个极端的骇客.有更简单的选择吗?

That sounds like an extreme hack to me. Is there a simpler option available?

推荐答案

在gRPC Java中,生成的代码和原型是可选的,并且实际上不需要它们(尽管它们很方便).要动态解释消息,您将需要定义自己的 Marshaller ,它与InputStream一起使用以访问原始消息字节.从这里,您可以将它们缓冲到一个数组中,并决定如何解析它们.

In gRPC Java, the generated code and the protos are optional, and you don't actually need them (though they are convenient). To dynamically interpret the message you will need to define your own Marshaller, which works with an InputStream to access the raw message bytes. From here you can buffer them into an array, and decide how to parse them.

作为类似的练习,我写了一篇更深入的教程,介绍如何将 JSON与gRPC一起使用.该原理应与您的代码相同.

As a similar exercise, I wrote a more in depth tutorial on using JSON with gRPC. The principle should be the same for your code.

这篇关于如何发送在运行时确定格式的gRPC消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!