首頁 > 後端開發 > Golang > 主體

RPC 操作 EPU 使用 Protobuf 並建立自訂插件

王林
發布: 2024-09-09 20:30:10
原創
270 人瀏覽過

RPC Action EPUsing Protobuf and Creating a Custom Plugin

上一篇文章中,我使用net/rpc包實現了一個簡單的RPC接口,並嘗試了net/rpc自帶的Gob編碼和JSON編碼,學習了Golang的一些基礎知識遠端過程呼叫。在這篇文章中,我將結合 net/rpc 和 protobuf 並創建我的 protobuf 外掛程式來幫助我們產生程式碼,所以讓我們開始吧。

本文首發於Medium MPP計畫。如果您是 Medium 用戶,請在 Medium 上關注我。非常感謝。

我們在工作上肯定使用過gRPC和protobuf,但是它們並沒有綁定。 gRPC可以使用JSON編碼,protobuf可以使用其他語言實作。

協定緩衝區Protobuf)是一種免費開源跨平台資料格式,用於序列化結構化資料。它對於開發透過網路相互通訊或儲存資料的程式很有用。該方法涉及一種描述某些資料結構的介面描述語言和一個根據該描述生成原始程式碼的程序,用於生成或解析表示結構化資料的位元組流。

使用 protobuf 的範例

首先我們寫一個原型檔案 hello-service.proto ,它定義了一則訊息「String」

syntax = "proto3";
package api;
option  go_package="api";

message String {
  string value = 1;
}
登入後複製

然後使用 protoc 實用程式產生訊息字串的 Go 程式碼

protoc --go_out=. hello-service.proto
登入後複製

然後我們修改 Hello 函數的參數以使用 protobuf 檔案產生的字串。

type HelloServiceInterface = interface {  
    Hello(request api.String, reply *api.String) error  
}  
登入後複製

使用起來和以前沒有什麼不同,甚至不如直接使用string那麼方便。那我們為什麼要使用protobuf呢?如我前面所說,使用Protobuf定義與語言無關的RPC服務介面和訊息,然後使用protoc工具產生不同語言的程式碼,才是它真正的價值所在。例如使用官方插件protoc-gen-go產生gRPC程式碼。

protoc --go_out=plugins=grpc. hello-service.proto
登入後複製

protoc 的插件系統

要從 protobuf 檔案產生程式碼,我們必須安裝 protoc ,但是 protoc 不知道我們的目標語言是什麼,所以我們需要外掛程式來幫助我們產生程式碼。 protoc的插件系統如何運作?以上面的grpc為例。

這裡有一個--go_out參數。由於我們所呼叫的插件是protoc-gen-go,因此參數稱為go_out;如果名稱是 XXX,則該參數將被稱為 XXX_out。

protoc執行時,首先會解析protobuf文件,產生一組Protocol Buffers編碼的描述性資料。它首先會判斷protoc中是否包含go插件,然後會嘗試在$PATH中尋找protoc-gen-go,如果找不到就會報錯,然後將運行 protoc-gen-go。 protoc-gen-go 命令並透過 stdin 將描述資料傳送到插件命令。插件產生檔案內容後,會將 Protocol Buffers 編碼的資料輸入到 stdout,告訴 protoc 產生特定的檔案。

plugins=grpc 是 protoc-gen-go 附帶的插件,以便調用它。如果你不使用它,它只會在Go中產生一條訊息,但你可以使用這個插件來產生grpc相關的程式碼。

自訂協定插件

如果我們在protobuf中加入Hello介面計時,是不是可以自訂一個protoc外掛程式來直接產生程式碼?

syntax = "proto3";  
package api;  
option  go_package="./api";  
service HelloService {  
  rpc Hello (String) returns (String) {}  
}  
message String {  
  string value = 1;
}
登入後複製

客觀的

對於本文,我的目標是建立一個插件,然後用於產生 RPC 伺服器端和客戶端程式碼,如下所示。

// HelloService_rpc.pb.go
type HelloServiceInterface interface {  
    Hello(String, *String) error  
}  

func RegisterHelloService(  
    srv *rpc.Server, x HelloServiceInterface,  
) error {  
    if err := srv.RegisterName("HelloService", x); err != nil {  
       return err  
    }  
    return nil  
}  

type HelloServiceClient struct {  
    *rpc.Client  
}  

var _ HelloServiceInterface = (*HelloServiceClient)(nil)  

func DialHelloService(network, address string) (  
    *HelloServiceClient, error,  
) {  
    c, err := rpc.Dial(network, address)  
    if err != nil {  
       return nil, err  
    }  
    return &HelloServiceClient{Client: c}, nil  
}  

func (p *HelloServiceClient) Hello(  
    in String, out *String,  
) error {  
    return p.Client.Call("HelloService.Hello", in, out)  
}
登入後複製

這會將我們的業務代碼更改為如下所示

// service
func main() {  
    listener, err := net.Listen("tcp", ":1234")  
    if err != nil {  
       log.Fatal("ListenTCP error:", err)  
    }  
    _ = api.RegisterHelloService(rpc.DefaultServer, new(HelloService))  
    for {  
       conn, err := listener.Accept()  
       if err != nil {  
          log.Fatal("Accept error:", err)  
       }  
       go rpc.ServeConn(conn)  
    }  
}  

type HelloService struct{}  

func (p *HelloService) Hello(request api.String, reply *api.String) error {  
    log.Println("HelloService.proto Hello")  
    *reply = api.String{Value: "Hello:" + request.Value}  
    return nil  
}
// client.go
func main() {  
    client, err := api.DialHelloService("tcp", "localhost:1234")  
    if err != nil {  
       log.Fatal("net.Dial:", err)  
    }  
    reply := &api.String{}  
    err = client.Hello(api.String{Value: "Hello"}, reply)  
    if err != nil {  
       log.Fatal(err)  
    }  
    log.Println(reply)  
}
登入後複製

從產生的程式碼來看,我們的工作量已經小很多了,出錯的機會也已經很小了。一個好的開始。

根據上面的api程式碼,我們可以拉出一個模板檔:

const tmplService = `  
import (  
    "net/rpc")  
type {{.ServiceName}}Interface interface {  
func Register{{.ServiceName}}(  
    if err := srv.RegisterName("{{.ServiceName}}", x); err != nil {        return err    }    return nil}  
    *rpc.Client}  
func Dial{{.ServiceName}}(network, address string) (  
{{range $_, $m := .MethodList}}  
    return p.Client.Call("{{$root.ServiceName}}.{{$m.MethodName}}", in, out)}  
`
登入後複製

整個模板很清晰,裡面有一些佔位符,像是MethodName、ServiceName等,我們稍後會介紹。

如何開發插件?

Google 發布了 Go 語言 API 1,引入了新的套件 google.golang.org/protobuf/compile R/protogen,大大降低了外掛程式開發的難度:

  1. First of all, we create a go language project, such as protoc-gen-go-spprpc
  2. Then we need to define a protogen.Options, then call its Run method, and pass in a func(*protogen.Plugin) error callback. This is the end of the main process code.
  3. We can also set the ParamFunc parameter of protogen.Options, so that protogen will automatically parse the parameters passed by the command line for us. Operations such as reading and decoding protobuf information from standard input, encoding input information into protobuf and writing stdout are all handled by protogen. What we need to do is to interact with protogen.Plugin to implement code generation logic.

The most important thing for each service is the name of the service, and then each service has a set of methods. For the method defined by the service, the most important thing is the name of the method, as well as the name of the input parameter and the output parameter type. Let's first define a ServiceData to describe the meta information of the service:

// ServiceData 
type ServiceData struct {  
    PackageName string  
    ServiceName string  
    MethodList  []Method  
}
// Method 
type Method struct {  
    MethodName     string  
    InputTypeName  string  
    OutputTypeName string  
}
登入後複製

Then comes the main logic, and the code generation logic, and finally the call to tmpl to generate the code.

func main() {  
    protogen.Options{}.Run(func(gen *protogen.Plugin) error {  
       for _, file := range gen.Files {  
          if !file.Generate {  
             continue  
          }  
          generateFile(gen, file)  
       }  
       return nil  
    })  
}  

// generateFile function definition
func generateFile(gen *protogen.Plugin, file *protogen.File) {  
    filename := file.GeneratedFilenamePrefix + "_rpc.pb.go"  
    g := gen.NewGeneratedFile(filename, file.GoImportPath)  
    tmpl, err := template.New("service").Parse(tmplService)  
    if err != nil {  
       log.Fatalf("Error parsing template: %v", err)  
    }  
    packageName := string(file.GoPackageName)  
// Iterate over each service to generate code
    for _, service := range file.Services {  
       serviceData := ServiceData{  
          ServiceName: service.GoName,  
          PackageName: packageName,  
       }  
       for _, method := range service.Methods {  
          inputType := method.Input.GoIdent.GoName  
          outputType := method.Output.GoIdent.GoName  

          serviceData.MethodList = append(serviceData.MethodList, Method{  
             MethodName:     method.GoName,  
             InputTypeName:  inputType,  
             OutputTypeName: outputType,  
          })  
       }  
// Perform template rendering
       err = tmpl.Execute(g, serviceData)  
       if err != nil {  
          log.Fatalf("Error executing template: %v", err)  
       }  
    }  
}
登入後複製

Debug plugin

Finally, we put the compiled binary execution file protoc-gen-go-spprpc in $PATH, and then run protoc to generate the code we want.

protoc --go_out=.. --go-spprpc_out=.. HelloService.proto
登入後複製

Because protoc-gen-go-spprpc has to depend on protoc to run, it's a bit tricky to debug. We can use

fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
登入後複製

To print the error log to debug.

Summary

That's all there is to this article. We first implemented an RPC call using protobuf and then created a protobuf plugin to help us generate the code. This opens the door for us to learn protobuf + RPC, and is our path to a thorough understanding of gRPC. I hope everyone can master this technology.

Reference

  1. https://taoshu.in/go/create-protoc-plugin.html
  2. https://chai2010.cn/advanced-go-programming-book/ch4-rpc/ch4-02-pb-intro.html

以上是RPC 操作 EPU 使用 Protobuf 並建立自訂插件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!