Tindakan RPC EPUMenggunakan Protobuf dan Mencipta Pemalam Tersuai

王林
Lepaskan: 2024-09-09 20:30:10
asal
287 orang telah melayarinya

RPC Action EPUsing Protobuf and Creating a Custom Plugin

Dalam artikel sebelumnya, saya melaksanakan antara muka RPC mudah menggunakan pakej net/rpc dan mencuba pengekodan Gob yang disertakan dengan pengekodan net/rpc dan JSON untuk mempelajari beberapa asas Golang RPC. Dalam siaran ini, saya akan menggabungkan net/rpc dengan protobuf dan mencipta pemalam protobuf saya untuk membantu kami menjana kod, jadi mari mulakan.

Artikel ini pertama kali diterbitkan dalam pelan MPP Sederhana. Jika anda pengguna Medium, sila ikuti saya di Medium. Terima kasih banyak-banyak.

Kami mesti menggunakan gRPC dan protobuf semasa bekerja, tetapi ia tidak terikat. gRPC boleh dikodkan menggunakan JSON dan protobuf boleh dilaksanakan dalam bahasa lain.

Penimbal Protokol (Protobuf) ialah format data merentas platform sumber terbuka yang digunakan untuk mensirikan data berstruktur. Ia berguna dalam membangunkan program yang berkomunikasi antara satu sama lain melalui rangkaian atau untuk menyimpan data. Kaedah ini melibatkan bahasa perihalan antara muka yang menerangkan struktur sesetengah data dan program yang menjana kod sumber daripada penerangan tersebut untuk menjana atau menghuraikan aliran bait yang mewakili data berstruktur.

Contoh penggunaan protobuf

Mula-mula kami menulis fail proto hello-service.proto yang mentakrifkan mesej "String"

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

message String {
  string value = 1;
}
Salin selepas log masuk

Kemudian gunakan utiliti protoc untuk menjana kod Go untuk String mesej

protoc --go_out=. hello-service.proto
Salin selepas log masuk

Kemudian kami mengubah suai argumen fungsi Hello untuk menggunakan String yang dijana oleh fail protobuf.

type HelloServiceInterface = interface {  
    Hello(request api.String, reply *api.String) error  
}  
Salin selepas log masuk

Menggunakannya tidak berbeza dengan sebelumnya, malah, ia tidak semudah menggunakan tali secara terus. Jadi mengapa kita perlu menggunakan protobuf? Seperti yang saya katakan sebelum ini, menggunakan Protobuf untuk mentakrifkan antara muka dan mesej perkhidmatan RPC bebas bahasa, dan kemudian menggunakan alat protok untuk menjana kod dalam bahasa yang berbeza, di mana nilai sebenarnya terletak. Contohnya, gunakan pemalam rasmi protoc-gen-go untuk menjana kod gRPC.

protoc --go_out=plugins=grpc. hello-service.proto
Salin selepas log masuk

Sistem pemalam untuk protoc

Untuk menjana kod daripada fail protobuf, kami mesti memasang protoc , tetapi protoc tidak mengetahui bahasa sasaran kami, jadi kami memerlukan pemalam untuk membantu kami menjana kod. bagaimana sistem pemalam protoc berfungsi? Ambil grpc di atas sebagai contoh.

Terdapat parameter --go_out di sini. Memandangkan pemalam yang kami panggil ialah protoc-gen-go, parameter dipanggil go_out; jika nama itu XXX, parameter akan dipanggil XXX_out.

Apabila protoc sedang berjalan, ia akan menghuraikan fail protobuf terlebih dahulu dan menjana satu set data deskriptif yang dikodkan oleh Protocol Buffers. Mula-mula ia akan menentukan sama ada pemalam go disertakan dalam protoc atau tidak, dan kemudian ia akan cuba mencari protoc-gen-go dalam $PATH, dan jika ia tidak menemuinya, ia akan melaporkan ralat, dan kemudian ia akan menjalankan protoc-gen-go. perintah protoc-gen-go dan menghantar data penerangan kepada arahan pemalam melalui stdin. Selepas pemalam menjana kandungan fail, ia kemudian memasukkan data yang dikodkan Penampan Protokol ke stdout untuk memberitahu protok untuk menjana fail tertentu.

plugins=grpc ialah pemalam yang disertakan dengan protoc-gen-go untuk menggunakannya. Jika anda tidak menggunakannya, ia hanya akan menjana mesej dalam Go, tetapi anda boleh menggunakan pemalam ini untuk menjana kod berkaitan grpc.

Sesuaikan pemalam protoc

Jika kami menambahkan pemasaan antara muka Hello pada protobuf, bolehkah kami menyesuaikan pemalam protoc untuk menjana kod terus?

syntax = "proto3";  
package api;  
option  go_package="./api";  
service HelloService {  
  rpc Hello (String) returns (String) {}  
}  
message String {  
  string value = 1;
}
Salin selepas log masuk

Objektif

Untuk artikel ini, matlamat saya adalah untuk mencipta pemalam yang kemudiannya akan digunakan untuk menjana kod bahagian pelayan dan pelanggan RPC yang kelihatan seperti ini.

// 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)  
}
Salin selepas log masuk

Ini akan menukar kod perniagaan kami supaya kelihatan seperti berikut

// 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)  
}
Salin selepas log masuk

Berdasarkan kod yang dijana, beban kerja kami sudah jauh lebih kecil dan kemungkinan ralat sudah sangat kecil. Permulaan yang baik.

Berdasarkan kod api di atas, kita boleh mengeluarkan fail templat:

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)}  
`
Salin selepas log masuk

Keseluruhan templat adalah jelas dan terdapat beberapa ruang letak di dalamnya, seperti MethodName, ServiceName, dsb., yang akan kami bincangkan kemudian.

Bagaimana untuk membangunkan pemalam?

Google mengeluarkan API bahasa Go 1, yang memperkenalkan pakej baharu google.golang.org/protobuf/compile R/protogen, yang sangat mengurangkan kesukaran pembangunan pemalam:

  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  
}
Salin selepas log masuk

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)  
       }  
    }  
}
Salin selepas log masuk

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
Salin selepas log masuk

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)
Salin selepas log masuk

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

Atas ialah kandungan terperinci Tindakan RPC EPUMenggunakan Protobuf dan Mencipta Pemalam Tersuai. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!