go中的protobuf和grpc使用教程
一、Protobuf
Protobuf是接口規(guī)范的描述語(yǔ)言,可以通過(guò)工具生成代碼,將結(jié)構(gòu)化數(shù)據(jù)序列化。
二、grpc
gRPC 是 Google 公司基于 Protobuf 開(kāi)發(fā)的跨語(yǔ)言的開(kāi)源 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
編譯生成目標(biāo)文件
3.3 grpc provider 實(shí)現(xiàn)
// 定義提供者 type StudentService struct { student.UnimplementedStudentServiceServer `wire:"-"` } // 實(shí)現(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 實(shí)現(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)) // 注冊(cè)grpc服務(wù) student.RegisterStudentServiceServer(server, &StudentService{}) // grpc 啟動(dòng) server.Serve(lis) }
3.5 grpc client 實(shí)現(xiàn)
func main_grpc() { <-time.NewTimer(time.Second * 2).C // 這里啟動(dòng)一個(gè)消費(fèi)者 conn, _ := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials())) defer conn.Close() cli := student.NewStudentServiceClient(conn) // 3秒讀超時(shí) 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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧
這篇文章主要為大家介紹了GoFrame?gmap遍歷hashmap?listmap?treemap使用技巧的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06golang實(shí)現(xiàn)對(duì)JavaScript代碼混淆
在Go語(yǔ)言中,你可以使用一些工具來(lái)混淆JavaScript代碼,一個(gè)常用的工具是Terser,它可以用于壓縮和混淆JavaScript代碼,你可以通過(guò)Go語(yǔ)言的`os/exec`包來(lái)調(diào)用Terser工具,本文給通過(guò)一個(gè)簡(jiǎn)單的示例給大家介紹一下,感興趣的朋友可以參考下2024-01-01Golang 如何實(shí)現(xiàn)函數(shù)的任意類(lèi)型傳參
這篇文章主要介紹了Golang 實(shí)現(xiàn)函數(shù)的任意類(lèi)型傳參操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04Golang連接池的幾種實(shí)現(xiàn)案例小結(jié)
這篇文章主要介紹了Golang連接池的幾種實(shí)現(xiàn)案例小結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03go語(yǔ)言轉(zhuǎn)換json字符串為json數(shù)據(jù)的實(shí)現(xiàn)
本文主要介紹了go語(yǔ)言轉(zhuǎn)換json字符串為json數(shù)據(jù)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-03-03