Grpc-Golang&Grpc-Java

这篇笔记主要是记录学习历程而不是怎么用~,以及protobuffers 和 gprc 各种文档的地址,等过上大半年后通过这篇笔记帮助自己快速重新掌握这个技术点


一、Protocolbuffers

关于protocolbuffers原来有写过一篇笔记质量还不错,本篇笔记就不重复写了:点击查看

下面记录下:protocbuffers在mac上安装时踩的坑

官网: https://developers.google.com/protocol-buffers

protoc下载地址:https://github.com/protocolbuffers/protobuf/releases

搞清楚自己在干什么~ 我们可以将protobuf理解成是一种协议。按照他的语法规范写好xxx.proto 文件后,使用protoc才能将其编译生成特定语言的代码~ 所以说这个protoc肯定免不了安装

下载之后为了方便使用,去 ~/.bash_profile 中添加PATH

vim ~/.bash_profile

#添加如下内容:
export PATH:/Users/dxm/protobuf/protoc-3.12.2-osx-x86_64/bin/protoc

# 使环境变量立即生效
source .bash_profile

# 校验是否识别protoc命令
which protoc
/Users/dxm/protobuf/protoc-3.12.2-osx-x86_64/bin/protoc

但是我发现将变量配置进~/.bash_profile 中总是会话级别的,换个窗口就不管用了。

所以推荐使用 ~/.zshrc 进行配置。如果没有的话,手动新建一个也无妨。

上面的protoc可以生成大部分语言的代码了,如果想要生成针对特定语言的代码,点击这个链接:https://github.com/protocolbuffers/protobuf/releases

二、Grpc

2.1 About-Java

  • github地址(从里面可以找到jar包和代码生成的插件):https://github.com/grpc/

    • 通过命令: mvn compile 进行编译
    • 通过maven编译生成代码的前提:我们需要将编写的 xxx.proto 文件放置到/src/main/目录下
    • 编译处理来的产物位于: target/generated-sources/
  • GrpcServer 和 GrpcStub之间可以用哪些方式交互数据?

    • 交互对象信息
    • stub发送obj,server返回stream
    • stub发送stream,server返回obj
    • stub和server之间通过stream交互

下面贴出关于Java使用Grpc的示例:

proto定义:https://github.com/zhuchangwu/oa-springboot/tree/master/src/protobuf

测试代码:https://github.com/zhuchangwu/oa-springboot/tree/master/src/test/java/com/changwu/flowCenterTest

2.2 About-Golang

首先是编写xxx.proto文件

执行如下命令下载插件,它能将xxx.protof编译成GO:

# protoc-gen-go 会被下载进/go/bin/

go get github.com/golang/protobuf/protoc-gen-go


# 如果不能用google:按下面的步骤来做

首先下载源代码包 : https://github.com/golang/protobuf
golang/protobuf

下载的zip然后解压到$GOPATH/src/http://github.com/golang/下

cd protobuf/protoc-gen-go 

go build
go install

快速开始:参照grpc官网(里面有demo,以及将xxx.proto编译成go代码的命令https://www.grpc.io/docs/languages/go/quickstart/

使用golang完成client和server之间的四种通信模式:https://github.com/zhuchangwu/oa-golang-flow-center/commits/master

补充:
protoc --go_out=plugins=grpc:. --proto_path=/Users/dxm/go/src/ --proto_path=./ yyy.proto

--go_out: 指定了生成的go文件的目录
--proto_path: 指定了要去哪个目录中搜索import中导入的和要编译为.go的proto文件,可以定义多个,第一个指定了import "xxx.proto"中xxx.proto文件的搜索目录
第二个定义了要编译的文件yyy.proto文件的目录。

posted @ 2020-06-06 20:12  赐我白日梦  阅读(613)  评论(0编辑  收藏  举报