当前位置: 代码网 > it编程>前端脚本>Golang > go中的protobuf和grpc使用教程

go中的protobuf和grpc使用教程

2024年09月06日 Golang 我要评论
一、protobuf protobuf是接口规范的描述语言,可以通过工具生成代码,将结构化数据序列化。二、grpcgrpc 是 google 公司基于 protobuf 开发的跨语言的开源 rpc

一、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()
	// 创建listener
	lis, _ := 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)
}

到此这篇关于go中的protobuf和grpc的文章就介绍到这了,更多相关go protobuf和grpc内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com