栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go集成grpc

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go集成grpc

go集成grpc 一,准备条件 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 得到

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

通过命令 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1 得到

1.4 总结

grpc参考官网 https://www.grpc.io/。把这些exe文件都加到环境变量

二,项目 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 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 大功告成,打道回府
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/904349.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号