搜尋
首頁後端開發GolangRPC 操作 EPU 使用 Protobuf 並建立自訂插件

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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何使用PPROF工具分析GO性能?您如何使用PPROF工具分析GO性能?Mar 21, 2025 pm 06:37 PM

本文解釋瞭如何使用PPROF工具來分析GO性能,包括啟用分析,收集數據並識別CPU和內存問題等常見的瓶頸。

Debian OpenSSL有哪些漏洞Debian OpenSSL有哪些漏洞Apr 02, 2025 am 07:30 AM

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

您如何在GO中編寫單元測試?您如何在GO中編寫單元測試?Mar 21, 2025 pm 06:34 PM

本文討論了GO中的編寫單元測試,涵蓋了最佳實踐,模擬技術和有效測試管理的工具。

如何編寫模擬對象和存根以進行測試?如何編寫模擬對象和存根以進行測試?Mar 10, 2025 pm 05:38 PM

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

如何定義GO中仿製藥的自定義類型約束?如何定義GO中仿製藥的自定義類型約束?Mar 10, 2025 pm 03:20 PM

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

解釋GO反射軟件包的目的。您什麼時候使用反射?績效有什麼影響?解釋GO反射軟件包的目的。您什麼時候使用反射?績效有什麼影響?Mar 25, 2025 am 11:17 AM

本文討論了GO的反思軟件包,用於運行時操作代碼,對序列化,通用編程等有益。它警告性能成本,例如較慢的執行和更高的內存使用,建議明智的使用和最佳

如何使用跟踪工具了解GO應用程序的執行流?如何使用跟踪工具了解GO應用程序的執行流?Mar 10, 2025 pm 05:36 PM

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化

您如何在GO中使用表驅動測試?您如何在GO中使用表驅動測試?Mar 21, 2025 pm 06:35 PM

本文討論了GO中使用表驅動的測試,該方法使用測試用例表來測試具有多個輸入和結果的功能。它突出了諸如提高的可讀性,降低重複,可伸縮性,一致性和A

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),