一、protobuf
protobuf是接口规范的描述语言,可以通过工具生成代码,将结构化数据序列化。
二、grpc
grpc 是 google 公司基于 protobuf 开发的跨语言的开源 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 // 创造grpc服务端 server := grpc.newserver() // 创建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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论