欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > go之protobuf和grpc

go之protobuf和grpc

2024/10/24 6:29:54 来源:https://blog.csdn.net/qq_37011724/article/details/141032944  浏览:    关键词: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

 protoc --proto_path=./third_party --proto_path=.  --go_out=.  --go-grpc_out=.   student.proto 

 编译生成目标文件

3.3 grpc provider 实现
// 定义提供者
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 实现
func main_grpc() {serverPort := 50051// 创造grpc服务端server := grpc.NewServer()// 创建listenerlis, _ := net.Listen("tcp", fmt.Sprintf(":%d", serverPort))// 注册grpc服务student.RegisterStudentServiceServer(server, &StudentService{})// grpc 启动server.Serve(lis)
}
3.5 grpc client 实现
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)}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com