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)

}
相关推荐
wei_shuo33 分钟前
飞算 JavaAI 开发助手:深度学习驱动下的 Java 全链路智能开发新范式
java·开发语言·飞算javaai
熊猫钓鱼>_>33 分钟前
用Python解锁图像处理之力:从基础到智能应用的深度探索
开发语言·图像处理·python
寻月隐君44 分钟前
Rust 异步编程实践:从 Tokio 基础到阻塞任务处理模式
后端·rust·github
GO兔44 分钟前
开篇:GORM入门——Go语言的ORM王者
开发语言·后端·golang·go
Sincerelyplz1 小时前
【Temproal】快速了解Temproal的核心概念以及使用
笔记·后端·开源
爱上语文1 小时前
Redis基础(6):SpringDataRedis
数据库·redis·后端
Lemon程序馆1 小时前
速通 GO 垃圾回收机制
后端·go
Aurora_NeAr1 小时前
Spark SQL架构及高级用法
大数据·后端·spark
杰尼橙子1 小时前
DPDK BPF:将eBPF虚拟机的灵活性带入到了DPDK的高性能用户态
后端·性能优化
好开心啊没烦恼1 小时前
Python 数据分析:numpy,抽提,整数数组索引与基本索引扩展(元组传参)。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy·pandas