go中的protobuf和grpc使用教程
一、Protobuf
Protobuf是接口規(guī)范的描述語言,可以通過工具生成代碼,將結(jié)構(gòu)化數(shù)據(jù)序列化。
二、grpc
gRPC 是 Google 公司基于 Protobuf 開發(fā)的跨語言的開源 RPC 框架。
三、使用教程
3.1 student.proto
syntax = "proto3"; import "google/api/annotations.proto"; package main; option go_package = "/main;student"; message Student { string name = 1; int32 age = 2; repeated int32 scores = 3; } service StudentService { rpc GetStudent(Student) returns (Student){ option (google.api.http) = { post: "/v1/student/get" body: "*" }; }; }
3.2 根據(jù)proto文件生成接口和結(jié)構(gòu)定義
third_party 存放annotations.proto
protoc --proto_path=./third_party --proto_path=. --go_out=. --go-grpc_out=. student.proto
編譯生成目標文件
3.3 grpc provider 實現(xiàn)
// 定義提供者 type StudentService struct { student.UnimplementedStudentServiceServer `wire:"-"` } // 實現(xiàn)提供者方法 func (s *StudentService) GetStudent(context.Context, *student.Student) (*student.Student, error) { return &student.Student{ Age: 18, Name: "vicyor", Scores: []int32{1, 2, 3, 4, 5}, }, nil }
3.4 grpc server 實現(xiàn)
func main_grpc() { serverPort := 50051 // 創(chuàng)造grpc服務(wù)端 server := grpc.NewServer() // 創(chuàng)建listener lis, _ := net.Listen("tcp", fmt.Sprintf(":%d", serverPort)) // 注冊grpc服務(wù) student.RegisterStudentServiceServer(server, &StudentService{}) // grpc 啟動 server.Serve(lis) }
3.5 grpc client 實現(xiàn)
func main_grpc() { <-time.NewTimer(time.Second * 2).C // 這里啟動一個消費者 conn, _ := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials())) defer conn.Close() cli := student.NewStudentServiceClient(conn) // 3秒讀超時 ctx, _ := context.WithTimeout(context.Background(), time.Second*3) res, _ := cli.GetStudent(ctx, &student.Student{}) fmt.Println(res) }
到此這篇關(guān)于go中的protobuf和grpc的文章就介紹到這了,更多相關(guān)go protobuf和grpc內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧
這篇文章主要為大家介紹了GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06Golang 如何實現(xiàn)函數(shù)的任意類型傳參
這篇文章主要介紹了Golang 實現(xiàn)函數(shù)的任意類型傳參操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04go語言轉(zhuǎn)換json字符串為json數(shù)據(jù)的實現(xiàn)
本文主要介紹了go語言轉(zhuǎn)換json字符串為json數(shù)據(jù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03