go集成grpc

go集成grpc的文章挺多的,可是,能从零开始让你完成集成的很少。所以,我就在踩坑中,把整个过程都趟了一遍。幸不辱命,这篇教程可以让你从零开始,把grpc完整地集成进入go中。

一,准备条件,把该下载的东西都下载下来。
1.1 下载protoc.exe

可以去 https://github.com/protocolbuffers/protobuf 下载

1.2 下载protoc-gen-go.exe

通过命令 go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26 得到,在goPath下的bin目录下

1.3 下载protoc-gen-go-grpc.exe

通过命令 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1 得到,在goPath下的bin目录下

1.4 总结

把这些exe文件都加到环境变量中(环境变量不知道怎么加的,请百度),grpc更多内容参考官网 https://www.grpc.io/。

二,项目实践
2.1 首先,我们要编写proto文件
syntax = "proto3";

package service;

option go_package = "go-test/pb/hello;hello";

message Req{
  int32 prod_id=1;
}

message Res{
  int32 prod_stock=1;
}

service Hello{
  rpc Hello(Req) returns (Res);
}
2.2 执行命令

go:generate这个命令是go执行命令行的一种方式,在终端直接执行go generate 就行了

//go:generate protoc --go_out=. --go_opt=paths=source_relative   --go-grpc_out=. --go-grpc_opt=paths=source_relative     ./pb/hello.proto

在这里插入图片描述

2.3 编写server
//生成或者更新 proto的go代码
//go:generate protoc --go_out=. --go_opt=paths=source_relative   --go-grpc_out=. --go-grpc_opt=paths=source_relative     ./pb/hello.proto

func main()  {
	startServer()
}



func startServer(){
	l, err := net.Listen("tcp", ":9999")
	if err != nil{
		panic(err)
	}
	s := grpc.NewServer()
	hello.RegisterHelloServer(s,&rpcServer{})
	s.Serve(l)
}

type  rpcServer struct{
	hello.UnimplementedHelloServer
}

func (r *rpcServer) Hello(ctx context.Context,req *hello.Req) (res *hello.Res,err error){
	res = &hello.Res{ProdStock: 99}
	return res,nil
}
2.4 编写client测试类
//测试 提供的服务
func TestClient(t *testing.T) {
	log.Println("开始启动客户端")
	conn, err := grpc.Dial("localhost:9999",grpc.WithInsecure())
	if err !=nil{
		log.Fatalln(err)
	}
	defer conn.Close()
	client := hello.NewHelloClient(conn)
	res, err := client.Hello(context.Background(), &hello.Req{ProdId: 1})

	if err != nil{
		log.Fatalln(err)
	}

	fmt.Println(res)

}
2.5 大功告成,打道回府

其实,go集成grpc挺简单的。但是,麻烦就麻烦在,你在集成前,需要做很多的准备工作,当这些准备工作没做好,就怎么也搞不定的。而网上的大多教程都是直接集成,却把准备工作给忽略了。这就导致,读着挺简单,自己搞怎么也搞不了。

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐