Golang搭建grpc环境

简介

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示例

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

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

  3. 输出信息

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,成功

参考

GRPC 官方文档
Golang 下载
Go专家编程

相关推荐

  1. golang开发环境

    2024-03-10 04:08:05       45 阅读
  2. 编程笔记 Golang基础 006 Goland开发环境

    2024-03-10 04:08:05       35 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-10 04:08:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-10 04:08:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-10 04:08:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-10 04:08:05       18 阅读

热门阅读

  1. 如何清除keep-alive缓存

    2024-03-10 04:08:05       21 阅读
  2. AIGC安全研究简述(附资料下载)

    2024-03-10 04:08:05       22 阅读
  3. Webpack配置与运行基础教程

    2024-03-10 04:08:05       20 阅读
  4. Kafka整理-Kafka Streams

    2024-03-10 04:08:05       22 阅读
  5. IoT技术有什么好处——青创智通

    2024-03-10 04:08:05       21 阅读
  6. 建造者模式

    2024-03-10 04:08:05       22 阅读
  7. windows下安装python virtualenv 虚拟环境

    2024-03-10 04:08:05       18 阅读
  8. tomcat跨域问题CORS踩坑点

    2024-03-10 04:08:05       19 阅读