Java + Go + Grpc + submodule 示例

# 簡單的 Java 調用 Go Grpc 後端示例

通過 submodule 異構語言共用一套 proto 文件, 在 proto 中 import 其他的 proto 文件.

先參考 go 服務後端 [tanjunchen/grpc-test-demo](https://github.com/tanjunchen/grpc-test-demo)

## 技術說明

https://github.com/tanjunchen/grpc-test-demo

go + submodule(共享 git proto 文件庫) + grpc

## *.pb.go 文件編譯語句

protoc -I. --go_out=plugins=grpc,paths=source_relative:./gen/go/ your/service/v1/your_service.proto

在 go-grpc-proto/prod 終端下執行以下語句生成 prod.pb.go 文件, 其中 go-grpc-proto 是以 submodule 的形式共用第三方 git 庫,
prod.proto 引用了 status/status.proto 文件, 故需要 --proto_path=../status/status.proto 編譯參數.

protoc -I=. -I=../ --proto_path=../status/status.proto --go_out=plugins=grpc,paths=source_relative:../../src/prod/  prod.proto

在 go-grpc-proto/status 終端下執行以下語句生成 prod.pb.go 文件

protoc -I=.  --go_out=plugins=grpc,paths=source_relative:../../src/status status.proto

java 可以直接執行 proto-controller 下的 protobuf:compile 與 protobuf:compile-custom 命令.

## 目錄結構

```
├── client      # go 測試客戶端
│   └── main.go
├── go-grpc-proto       # 存放原始 proto 文件
│   ├── prod
│   │   └── prod.proto      # 說明 prod.proto 引用了 status 下的包
│   └── status
│       └── status.proto
├── go.mod      # mod 文件
├── README.md       # readme 文件
├── server      # go 服務器後端
│   └── main.go
├── service     # demo 示例
│   └── test_service.go
└── src     # 生成後的 *.pb.go 文件
    ├── prod
    │   └── prod.pb.go
    └── status
        └── status.pb.go
```

## 使用步驟

### go 到 go

git clone https://github.com/tanjunchen/grpc-test-demo.git
    
git submodule update --init --recursive

go mod tidy

cd server && go run main.go

```
Listen on 0.0.0.0:9999
```

server 端

```
Listen on 0.0.0.0:9999
211
```

client 端

```
prod_stock:211  status:{code:"200"  msg:"success"}
```

### java 到 go

參見 java [tanjunchen/Java-Go-Grpc-Demo](https://github.com/tanjunchen/Java-Go-Grpc-Demo)

啓動服務端同理
 
git clone https://github.com/tanjunchen/Java-Go-Grpc-Demo.git
 
git submodule update --init --recursive
 
cd src/main/java/com/ctj/SpringBootGRPCApplication.java

終端響應如下:

```
xxxxxx  INFO 20752 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
xxxxxx  INFO 20752 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1696 ms
xxxxxx  INFO 20752 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
xxxxxx  INFO 20752 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9998 (http) with context path ''
xxxxxx  INFO 20752 --- [           main] com.ctj.SpringBootGRPCApplication        : Started SpringBootGRPCApplication in 2.513 seconds (JVM running for 2.879)
prod_stock: 1000
status {
  code: "200"
  msg: "success"
}

200
success
```

java 推薦使用 https://github.com/yidongnan/grpc-spring-boot-starter 與 grpc 服務提供者通信.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章