当前位置: 代码网 > it编程>前端脚本>Golang > Golang搭建grpc环境的流程步骤

Golang搭建grpc环境的流程步骤

2024年05月18日 Golang 我要评论
简介os : windows 11 golang 版本: go1.22.0grpc : 1.2protobuffer: 1.28代理没有代理国内环境下载不了库七牛cdn (试过可用)go env -w

简介

os : windows 11 
golang 版本: go1.22.0
grpc : 1.2
protobuffer: 1.28

代理

没有代理国内环境下载不了库

七牛cdn (试过可用)
go env -w goproxy=https://goproxy.cn,direct

阿里云代理(运行grpc时下载包出现报错 ):
go env -w goproxy=https://mirrors.aliyun.com/goproxy/,direct

环境搭建步骤

1. 安装golang(略)

2. 设置gopath

默认gopath是 %userprofile%\go,%userprofile% 一般是 c:\users\administrator, 执行 go env gopath 可以查看到当前设置的gopath, 可以通过修改环境变量修改gopath, 例如下图

在这里插入图片描述

3. 设置代理

	执行如下指令, 设置代理
	go env -w goproxy=https://goproxy.cn,direct

4. 安装grpc组件

参考 grpc官方文档,
执行如下指令安装proto buffer和grpc的golang编译器
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2

安装之后gopath下就包含你安装的包了, 如下图

在这里插入图片描述

5. 下载protoc工具

上一个步骤只是下载了 proto buffer和grpc的golang编译器, 也可以说只是两个插件, 还需要protoc工具来进行调用, 由于我已经安装了, 所以这里提供一下下载路径, 再自行研究一下
protoc 工具下载

6. 编译grpc示例

下载grpc源码
git clone -b v1.62.0 --depth 1 https://github.com/grpc/grpc-go

执行示例
cd grpc-go/examples/helloworld
go run greeter_server/main.go ## 执行服务端
go run go run greeter_client/main.go ## 执行客户端

输出信息

server :

在这里插入图片描述

client :

在这里插入图片描述

7. 使用proto工具生成golang支持

4~5步下载了工具还没有使用上, 因为grpc-go的代码示例已经生成好了,在xx\grpc-go\examples\helloworld\helloworld 目录下, 如下图

在这里插入图片描述

将 helloworld.pb.go 和 helloworld_grpc.pb.go 删除或移到备份目录, 我们使用前面下载的工具重新生成一次
执行指令如下, 生成proto buffer的golang支持
d:\softwares\paths\msys64\mingw64\bin\protoc.exe --plugin=protoc-gen-go=d:/softwares/paths/golang/bin/protoc-gen-go.exe --go_out=. ./helloworld.proto
执行指令如下, 生成grpc的golang支持
d:\softwares\paths\msys64\mingw64\bin\protoc.exe --plugin=protoc-gen-go-grpc=d:/softwares/paths/golang/bin/protoc-gen-go-grpc.exe --go-grpc_out=. ./helloworld.proto

再次执行server, 出现错误如下

在这里插入图片描述

原因是刚刚生成的文件路径不是在helloworld/helloworld下, 而是生成到下图路径了,
note: 之所以如此是因为 helloworld.proto里的这一句
option go_package = “google.golang.org/grpc/examples/helloworld/helloworld”;

在这里插入图片描述

正确路径

在这里插入图片描述

再次执行server,成功

以上就是golang搭建grpc环境的流程步骤的详细内容,更多关于golang搭建grpc环境的资料请关注代码网其它相关文章!

(0)

相关文章:

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

发表评论

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