Skip to content

axliupore/grpc-learning

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

grpc-learning

本项目是通过一个简单的例子来学习 grpc,记录一下踩到的坑以及如何解决它们的。

安装

本示例是在 mac 上进行测试的,所以安装教程为 mac 的安装,如 Linux 和 Windows 在网上找对应的安装教程即可。

protobuf

这里直接使用 brew 工具安装

$ brew install protobuf

brew 默认会安装最新版本,执行 protoc 查看当前版本:

$ protoc --version
libprotoc 25.3

grpc-go

  • 要求 golang 版本 >= 1.6
$ go get -u google.golang.org/grpc

golang protobuf

  • 要求 golang 版本 > 1.4
  • 使用前要求安装 protobuf 编译器
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

解释

  • protoc:这是 protobuf 的编译器,用于将 .proto 文件编译成对应语言的源代码文件。
  • grpc-go:这是 grpc 的 golang 实现。
  • protoc-gen-go:是一个 google 提供的插件,用于将 protobuf 的 .proto 文件编译成 golang 的源代码文件。

使用

  1. 克隆本项目
$ git clone git@github.com:axliupore/grpc-learning.git 
  1. 进入到 hello 目录
$ cd hello  
  1. .proto 文件编译成 golang 源文件
$  protoc --go_out=. --go-grpc_out=.  hello.proto 
  1. 进入到 server 目录,启动服务端
$  go run main.go
2024/03/20 18:26:31 grpc server running :8080
  1. 进入到 client 目录,启动客户端
$ go run main.go
2024/03/20 18:30:46 name:"axliu"  age:"18" <nil> 

踩坑

未指定导出路径

输出以下内容:

protoc-gen-go: unable to determine Go import path for "hello.proto"

Please specify either:
        • a "go_package" option in the .proto source file, or
        • a "M" argument on the command line.

See https://developers.google.com/protocol-buffers/docs/reference/go-generated#package for more information.

--go_out: protoc-gen-go: Plugin failed with status code 1.

hello.proto 文件加入下面这段代码:

option go_package = "../hello"; // 指定存放生成的文件路径

命令参数错误

$  protoc -I . --go_out=plugins=grpc:. hello.proto 
--go_out: protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate gRPC

See https://grpc.io/docs/languages/go/quickstart/#regenerate-grpc-code for more information.

将命令修改为下面即可:

$ protoc --go_out=. --go-grpc_out=.  hello.proto     

Releases

No releases published

Packages

No packages published

Languages