go中的protobuf和grpc使用教程
更新時間:2024年08月13日 10:47:38 作者:卡卡舅舅
gRPC 是 Google 公司基于 Protobuf 開發(fā)的跨語言的開源 RPC 框架,這篇文章主要介紹了go中的protobuf和grpc使用教程,需要的朋友可以參考下
一、Protobuf
Protobuf是接口規(guī)范的描述語言,可以通過工具生成代碼,將結構化數據序列化。
二、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 根據proto文件生成接口和結構定義
third_party 存放annotations.proto
protoc --proto_path=./third_party --proto_path=. --go_out=. --go-grpc_out=. student.proto
編譯生成目標文件
3.3 grpc provider 實現
// 定義提供者 type StudentService struct { student.UnimplementedStudentServiceServer `wire:"-"` } // 實現提供者方法 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 實現
func main_grpc() { serverPort := 50051 // 創(chuàng)造grpc服務端 server := grpc.NewServer() // 創(chuàng)建listener lis, _ := net.Listen("tcp", fmt.Sprintf(":%d", serverPort)) // 注冊grpc服務 student.RegisterStudentServiceServer(server, &StudentService{}) // grpc 啟動 server.Serve(lis) }
3.5 grpc client 實現
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) }
到此這篇關于go中的protobuf和grpc的文章就介紹到這了,更多相關go protobuf和grpc內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧
這篇文章主要為大家介紹了GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06