gRPC Gateway

栏目: 服务器 · 发布时间: 7年前

内容简介:本文将向你介绍 gRPC Gateway。代码示例:grpc-gateway 是一个

本文将向你介绍 gRPC Gateway。代码示例: demo

简介

grpc-gateway 是一个 protoc 的插件。它读取 gRPC 服务定义,生成反向代理服务器,将 RESTful JSON API 翻译成 gRPC。

gRPC Gateway

安装

源码编译安装 Protocol Buffers v3

mkdir tmp
cd tmp
git clone https://github.com/google/protobuf
cd protobuf
./autogen.sh
./configure
make
make check
sudo make install

安装所需的 protoc 插件

go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
go get -u github.com/golang/protobuf/protoc-gen-go

使用

grpc-gateway 有两种使用方式:

  • 注解
  • 配置

原服务

例如我有下面这样一个 gRPC 服务。

syntax = "proto3";
package example;
message StringMessage {
  string value = 1;
}

service YourService {
  rpc Echo(StringMessage) returns (StringMessage) {}
}

使用注解

按照 +/- 提示修改 .proto 文件,给服务添加一个 option。

syntax = "proto3";
 package example;
+
+import "google/api/annotations.proto";
+
 message StringMessage {
   string value = 1;
 }

 service YourService {
-  rpc Echo(StringMessage) returns (StringMessage) {}
+  rpc Echo(StringMessage) returns (StringMessage) {
+    option (google.api.http) = {
+      post: "/v1/example/echo"
+      body: "*"
+    };
+  }
 }

使用配置

保持 .proto 文件不变,新建一个 your_service.yaml 写入服务相关配置。

type: google.api.Service
config_version: 3

http:
  rules:
    - selector: example.YourService.Echo
      post: /v1/example/echo
      body: '*'

以上所述就是小编给大家介绍的《gRPC Gateway》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Dive Into Python 3

Dive Into Python 3

Mark Pilgrim / Apress / 2009-11-6 / USD 44.99

Mark Pilgrim's Dive Into Python 3 is a hands-on guide to Python 3 (the latest version of the Python language) and its differences from Python 2. As in the original book, Dive Into Python, each chapter......一起来看看 《Dive Into Python 3》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具