Introduction to gRPC


Posted by Kled on 2021-10-28

Introduction to gRPC
這篇會介紹 gRPC and protocol buffers的基本

gRPC使用protocol buffers 當作 interface definition language(IDL)underlying message interchange format

Why we need gRPC

比起傳統的RPC, gRPC可以實現跨平台不同語言之間的對接
gRPC
上圖簡述了gRPC的特性
On server side, server要implement interface, 並且處理client的呼叫
On client side, client has a stub 讓他可以跟server做溝通

protocol buffers負責定義data structure跟interface

Working with Protocol Buffers

gRPC使用Protocol Buffers序列化結構data, 下面會介紹protocol buffer怎麼作用的

第一步是定義stucture of the data
會用.proto做結尾, Protocol buffer使用messages作為data structure, message裡面的data paris稱為fields
下面是範例

message Person {
    string name = 1;
    int32 id = 2;
    bool has_ponycopter = 3;
}

後面的數字是編碼, 用來做版本相容性用的, name這個key可以被後面的版本重複使用, 但編碼不行, 編碼只要使用過, 後續就不能再使用
一旦完成了這份data structure, 就可以透過protocol buffer compiler去產生data class in your languages(python, C++, Go...)

// The greeter service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

serivce裡面則是定義了interface, interface定義了要傳的資料格式以及要return的資料格式(messages)

gRPC本機溝通時間測試

測試使用python內建的example code去做溝通想要測試gRPC的溝通時間

class Greeter(helloworld_pb2_grpc.GreeterServicer):

    def SayHello(self, request, context):
        for i in range(1000000):
            a = 0
        return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)

並且跟實際本機跑比較時間差

for i in range(1000000):
    a = 0

最後透過RPC得到的結果

0.028870344161987305
0.02689981460571289
0.025292158126831055
0.024933576583862305

而本機測試出來的時間為

0.022965431213378906

可以看到除了第一次會較慢以外, 平均會多出0.002~0.02(多次測試的maximum), 對於本機運行的程式還是不小的負擔
所以使用gRPC還是要計算時間的tradeoff
或是可以使用更好的機台去做分散式運算

下一篇會更詳細介紹protobuf跟gRPC interface溝通的API


如果喜歡文章, 不妨按下喜歡訂閱支持

如果真的想支持我進行創作與實踐計畫, 也可以進行打賞
BTC (BTC) : 1LFRBqvWR9GGizBzoFddkb5xRpAzKRVoDC
BTC (BSC) : 0xe1cda3eb778d1751af17feac796a4bbe4dbca815
BTC (ERC20) : 0xe1cda3eb778d1751af17feac796a4bbe4dbca815
USDT (TRC20) : TT7wgKuYoHwfRy3vCr38Qy3gnS3JJ1aKvn

如果想使用幣安, 可以使用我的推薦連結可以節省手續費10%
或使用推薦碼 : A5YRMD2T


#gRPC #protobuf #protocol buffer #messages #service







Related Posts

[ Day 01 ] Python unittest 單元測試 | 專案應用分享

[ Day 01 ] Python unittest 單元測試 | 專案應用分享

Day 128

Day 128

How to Request an AWS SSL/TLS Certificate

How to Request an AWS SSL/TLS Certificate


Comments