ProtoBuf中service使用

在 Protocol Buffers 的 proto3 语法中,service 用于定义一个 gRPC 服务。一个 service 包含了一组可以远程调用的 RPC 方法,每个方法有请求类型和响应类型。

基本语法

protobuf 复制代码
syntax = "proto3";

service ServiceName {
    rpc MethodName(RequestType) returns (ResponseType);
}

// service ServiceName:定义服务的名称。
// rpc MethodName:定义 RPC 方法的名称。
// RequestType:请求消息类型。
// ResponseType:响应消息类型。

示例

下面是一个完整的proto3示例文件,定义了一个基于Chord的简单gRPC服务。

protobuf 复制代码
syntax = "proto3";

package protos;


// DHT Common RPCs

message Key {
    string key = 1;
}

message Pair {
    string key = 1;
    string value = 2;
}

message Result {
    string result = 1;
}

message Void {

}

message ControlRequest {
    string control = 1;
}

// Chord RPCs

message  FindSuccessorRequest {
    bytes id = 1;
}

message  Node {
    bytes id = 1;
    string addr = 2;
}

service Chord {
    rpc FindSuccessor (FindSuccessorRequest) returns (Node) {
    }

    rpc Notify (Node) returns (Result) {
    }

    rpc FindPredecessor (Node) returns (Node) {
    }

    rpc Ping (Node) returns (Void){
    }

}

带有流式的RPC的实例

proto3 还支持流式 RPC 方法,包括客户端流、服务端流和双向流:

protobuf 复制代码
syntax = "proto3";

package proto3;

// 请求消息类型
message StreamRequest {
    string data = 1;
}

// 响应消息类型
message StreamResponse {
    string data = 1;
}

// 定义一个带有流式 RPC 的 gRPC 服务
service Streamer {
    // 单向流,从客户端流向服务端
    rpc ClientStream (stream StreamRequest) returns (StreamResponse);
    
    // 单向流,从服务端流向客户端
    rpc ServerStream (StreamRequest) returns (stream StreamResponse);
    
    // 双向流,客户端和服务端都可以发送和接收流
    rpc BidirectionalStream (stream StreamRequest) returns (stream StreamResponse);
}

stream 关键字用于表示流式 RPC。

ClientStream 是客户端流式 RPC,客户端发送流数据,服务端返回单个响应。

ServerStream 是服务端流式 RPC,客户端发送单个请求,服务端返回流数据。

BidirectionalStream 是双向流式 RPC,客户端和服务端都可以发送和接收流数据。

最后给大家推荐一个LinuxC/C++高级架构系统教程的学习资源与课程,可以帮助你有方向、更细致地学习C/C++后端开发,具体内容请见 https://xxetb.xetslk.com/s/1o04uB

相关推荐
浅念-7 天前
C++ Protobuf 入门实战:基于通讯录项目吃透proto3语法与序列化
linux·服务器·网络·c++·protobuf·proto·proto3
Zenova EdgeOS13 天前
Go 工业边缘 Protobuf 实战:从 proto 到 Marshal 的完整落地
物联网·go·边缘计算·序列化·protobuf·工业边缘
++==15 天前
ProtoBuf:序列化与反序列化、基础数据结构、关键词、数据格式
序列化·protobuf
witton25 天前
xmake中将proto文件生成C/C++文件然后再编译链接进项目
c语言·c++·mingw·protobuf·xmake·protobuf-c·protoc-gen-c
寒水馨2 个月前
Linux下载、安装protobuf-v35.1(附安装包protoc-35.1-linux-x86_64.zip)
linux·运维·服务器·google·序列化·protobuf·protoc
寒水馨2 个月前
macOS下载、安装protobuf-v35.1(附安装包protoc-35.1-osx-universal_binary.zip)
macos·google·grpc·序列化·protobuf·protoc·数据交换
yinchnag3 个月前
Protobuf 存负数为什么这么费——sint32 与 ZigZag 编码
protobuf
yinchnag3 个月前
proto协议统计带宽字节流量
protobuf
十五年专注C++开发4 个月前
C++ 序列化 Protocol Buffers:高效数据交换
开发语言·c++·序列化·反序列化·protobuf
喵了几个咪4 个月前
统一范式:中后台Admin项目标准化API分层开发方案(Vue/React通用)
前端·vue.js·react.js·protobuf