go之protobuf和grpc

一、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

bash 复制代码
 protoc --proto_path=./third_party --proto_path=.  --go_out=.  --go-grpc_out=.   student.proto 

编译生成目标文件

3.3 grpc provider 实现
Go 复制代码
// 定义提供者
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 实现
Go 复制代码
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 实现
Go 复制代码
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)

}
相关推荐
lsx2024065 小时前
jEasyUI 条件设置行背景颜色
开发语言
飞天小蜈蚣5 小时前
python-django_ORM的十三个查询API接口
开发语言·python·django
飞雪20075 小时前
局域网服务发现技术, DNS-SD和mDNS具体有什么区别, 什么不同?
开发语言·局域网·mdns·airplay·dns-sd·airprint
开开心心就好5 小时前
打印机驱动搜索下载工具,自动识别手动搜
java·linux·开发语言·网络·stm32·物联网·电脑
张np5 小时前
java基础-ListIterator 接口
java·开发语言
Apifox.5 小时前
测试用例越堆越多?用 Apifox 测试套件让自动化回归更易维护
运维·前端·后端·测试工具·单元测试·自动化·测试用例
AndrewHZ5 小时前
【Python与生活】怎么用python画出好看的分形图?
开发语言·python·生活·可视化·递归·分形
陳10305 小时前
C++:继承
开发语言·c++
GSDjisidi5 小时前
正社員・個人事業主歓迎|GSD東京本社で働こう|業界トップクラスの福利厚生完備
开发语言·面试·职场和发展
xiaoye-duck5 小时前
C++ string 类使用超全攻略(下):修改、查找、获取及常见实用接口深度解析
开发语言·c++·stl