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)

}
相关推荐
程序员爱钓鱼18 分钟前
Go语言实战案例-判断一个数是否为质数
后端·google·go
程序员爱钓鱼23 分钟前
Go语言实战案例-读取本地文本文件内容
后端·google·go
古月-一个C++方向的小白4 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发5 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州6 小时前
Python笔记
开发语言·笔记·python
tanyongxi666 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
阿葱(聪)7 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java8 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展
斯是 陋室8 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
mCell8 小时前
Go 并发编程基础:从 Goroutine 到 Worker Pool 实践
后端·性能优化·go