grpc入门

2023/3/5 gogrpc

🌙 rpc

RPC(Remote Procedure Call)是一种远程过程调用协议,它允许程序调用另一个地址空间(通常是共享网络的另一台机器上)的过程或函数,而不用关心底层网络细节。在分布式应用中,RPC是常用的通信方式之一。

🌙 grpc

gRPC是一种高性能、开源和通用的远程过程调用(RPC)框架,它可以在任何地方运行。gRPC使客户端和服务器应用程序能够透明地通信,并简化了连接不同系统的复杂性。它基于HTTP/2协议标准设计,使用Protocol Buffers作为接口描述语言。

🌙 Protocol Buffers

Protocol Buffers是一种轻便高效的序列化数据结构的协议,它可以用于数据存储、通信协议等方面。它的优点是数据结构定义简单,序列化后的数据体积小,解析速度快,支持跨语言,适用于分布式系统中的数据交换和存储。

syntax = "proto3";

package example;

message Person {
  string name = 1;
  int32 age = 2;
  repeated string hobbies = 3;
}

// Define the gRPC service
service ExampleService {
  // Unary RPC method
  rpc GetPerson(PersonRequest) returns (PersonResponse) {}

  // Server streaming RPC method
  rpc ListPeople(ListPeopleRequest) returns (stream PersonResponse) {}

  // Client streaming RPC method
  rpc AddPeople(stream PersonRequest) returns (AddPeopleResponse) {}

  // Bidirectional streaming RPC method
  rpc Chat(stream ChatRequest) returns (stream ChatResponse) {}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

🌙 proto与struct

在Go语言中,可以使用protobuf库将.proto文件中定义的消息类型转换为Go语言中的struct类型,也可以将Go语言中的struct类型转换为.proto文件中定义的消息类型。这样,就可以在gRPC中使用定义好的消息类型进行通信了。具体的转换方法可以参考protobuf库的文档。