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)

}
相关推荐
爱海贼的无处不在17 分钟前
一个需求竟然要开14个会:程序员的日常到底有多“会”?
后端·程序员
IT_陈寒1 小时前
Java 性能优化:5个被低估的JVM参数让你的应用吞吐量提升50%
前端·人工智能·后端
南囝coding1 小时前
《独立开发者精选工具》第 018 期
前端·后端
绝无仅有1 小时前
数据库MySQL 面试之死锁与排查经验总结
后端·面试·github
用户384958730692 小时前
Spring Boot 集成 Redis 的完整流程
后端
昨日的风2 小时前
springboot 多数据源切换
后端
绝无仅有3 小时前
mysql性能优化实战与总结
后端·面试·github
用户8356290780513 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下3 小时前
最终的信号类
开发语言·c++·算法
德育处主任3 小时前
玩转 Strands:AI Agent 开发,原来可以这么简单!
后端·aigc