1

如何将数据传递给toniconeof中的 protobuf ?

我在文档中找不到任何说明或示例。

4

1 回答 1

2

Tonic 应该enum为每个oneof变体生成一个对应的类型。您必须对此进行匹配。


对于这个答案,我假设tonic = "0.4.3"和或更高。prost = "0.7.0"让我们以以下.proto定义为例:

syntax = "proto3";

package stack_overflow;

service StackOverflow {
  rpc Question (HelpRequest) returns (HelpResponse);
}

message HelpRequest {
  oneof foo {
    FroozleType froozle = 1;
    FrobnikType frobnik = 2;
  }
}

message FroozleType {
  int32 value = 1;
}
message FrobnikType {}

message HelpResponse {
  oneof bar {
    QuxType qux = 1;
    BazType baz = 2;
  }
}

message QuxType {
  int32 answer = 1;
}
message BazType {
  string comment = 1;
}

构建后,这会生成以下类型和特征。对于服务:

  • stack_overflow_server::StackOverflow: 服务器特性

对于请求:

  • HelpRequest: 请求消息的结构
  • help_request::Foo: 请求中的枚举,oneof foo具有一个Froozle和一个Frobnik变体
  • FroozleType:FroozleType消息的结构
  • FrobnikType:FrobnikType消息的结构

对于回复:

  • HelpResponse: 响应消息的结构
  • help_response::Baroneof bar:响应中的枚举,具有一个Qux和一个Baz变体
  • QuxType:QuxType消息的结构
  • BazType:BazType消息的结构

例如,HelpRequeststruct 和help_request::Fooenum 定义如下:

#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HelpRequest {
    #[prost(oneof = "help_request::Foo", tags = "1, 2")]
    pub foo: ::core::option::Option<help_request::Foo>,
}

/// Nested message and enum types in `HelpRequest`.
pub mod help_request {
    #[derive(Clone, PartialEq, ::prost::Oneof)]
    pub enum Foo {
        #[prost(message, tag = "1")]
        Froozle(super::FroozleType),
        #[prost(message, tag = "2")]
        Frobnik(super::FrobnikType),
    }
}

将它们放在一起,上述服务的示例实现可能如下所示:

use tonic::{Request, Response, Status};

mod grpc {
    tonic::include_proto!("stack_overflow");
}

#[derive(Debug)]
pub struct StackOverflowService {}

#[tonic::async_trait]
impl grpc::stack_overflow_server::StackOverflow for StackOverflowService {
    async fn question(
        &self,
        request: Request<grpc::HelpRequest>,
    ) -> Result<Response<grpc::HelpResponse>, Status> {
        let request = request.into_inner();

        let bar = match request.foo {
            Some(grpc::help_request::Foo::Froozle(froozle)) => {
                Some(grpc::help_response::Bar::Qux(grpc::QuxType {
                    answer: froozle.value + 42,
                }))
            }
            Some(grpc::help_request::Foo::Frobnik(_)) => {
                Some(grpc::help_response::Bar::Baz(grpc::BazType {
                    comment: "forty-two".into(),
                }))
            }
            None => None,
        };

        let reply = grpc::HelpResponse { bar };
        return Ok(Response::new(reply));
    }
}
于 2021-07-02T16:03:19.413 回答