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)文章
Hugo?Config模塊構(gòu)建實(shí)現(xiàn)源碼剖析
這篇文章主要為大家介紹了Hugo?Config模塊構(gòu)建實(shí)現(xiàn)源碼剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Go 互斥鎖和讀寫(xiě)互斥鎖的實(shí)現(xiàn)
本文主要介紹了Go 互斥鎖和讀寫(xiě)互斥鎖的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
學(xué)會(huì)提升Go語(yǔ)言編碼效率技巧拒絕加班!
這篇文章主要為大家介紹了Go語(yǔ)言編碼效率提升技巧詳解,學(xué)會(huì)了從此拒絕加班,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
GO語(yǔ)言(golang)基礎(chǔ)知識(shí)
這篇文章主要介紹了GO語(yǔ)言(golang)基礎(chǔ)知識(shí),需要的朋友可以參考下2015-01-01
go語(yǔ)言中切片與內(nèi)存復(fù)制 memcpy 的實(shí)現(xiàn)操作
這篇文章主要介紹了go語(yǔ)言中切片與內(nèi)存復(fù)制 memcpy 的實(shí)現(xiàn)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04
go語(yǔ)言程序cpu過(guò)高問(wèn)題排查的方法詳解
使用golang進(jìn)行復(fù)雜的組合運(yùn)算,導(dǎo)致CPU占用率非常高,下面這篇文章主要給大家介紹了關(guān)于go語(yǔ)言程序cpu過(guò)高問(wèn)題排查的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04

