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)

}
相关推荐
罗政12 分钟前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
迷迭所归处15 分钟前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ43 分钟前
Java 23 的12 个新特性!!
java·开发语言·学习
leon62544 分钟前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
拾光师2 小时前
spring获取当前request
java·后端·spring
锦亦之22332 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏2 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言
姜太公钓鲸2332 小时前
c++ static(详解)
开发语言·c++
菜菜想进步2 小时前
内存管理(C++版)
c语言·开发语言·c++
2301_789985942 小时前
Java语言程序设计基础篇_编程练习题*18.29(某个目录下的文件数目)
java·开发语言·学习