07 gRPC

81 阅读1分钟

image.png

image.png

image.png

image.png

image.png

How to define gRPC API and genarate Go code with protobuf.

  • Makefile
proto:
	protoc  --proto_path=proto  --go_out=pb  --go_opt=paths=source_relative \
    --go-grpc_out=pb    --go-grpc_opt=paths=source_relative \
    proto/*.proto

make proto生成/pb下的.pb.go代码,此时运行go mod tidy下载一些包。

How to run a gRPC server.

  • type SimpleBankServer interface

  • SimpleBankServer是SimpleBank服务的服务器API

  • 所有实现都必须嵌入UnimplementedSimpleBankServer

  • 以确保向前兼容性 image.png

  • type UnimplementedSimpleBankServer struct(未实现的SimpleBank服务器)

  • 必须被嵌入以实现向前兼容的实现 image.png

  • 使用evans evans --host localhost --port 9090 -r repl

image.png

gRPC GATEWAY

  1. 定义tools.go
// +build tools

package tools

import (
    _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway"
    _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2"
    _ "google.golang.org/grpc/cmd/protoc-gen-go-grpc"
    _ "google.golang.org/protobuf/cmd/protoc-gen-go"
)
  1. run go mod tidy to resolve the versions. Install by running
go install \
    github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \
    github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \
    google.golang.org/protobuf/cmd/protoc-gen-go \
    google.golang.org/grpc/cmd/protoc-gen-go-grpc
2ccfbafce26f# which protoc-gen-grpc-gateway
/root/go/bin/protoc-gen-grpc-gateway
  1. If you are using protoc to generate stubs, you need to ensure the required dependencies are available to the compiler at compile time. These can be found by manually cloning and copying the relevant files from the googleapis repository, and providing them to protoc when running. The files you will need are:
google/api/annotations.proto
google/api/field_behavior.proto
google/api/http.proto
google/api/httpbody.proto

先下载https://github.com/googleapis/googleapis.git

  • Makefile image.png