Go Grpc Gateway兼容HTTP协议文档自动生成网关


Posted in Golang onJune 16, 2022

前言

调用,让客户端可以更具自身情况自由选择,服务端工作只需要做一份呢?还别说真还有一个准备好的轮子那就是今天的主角《grpc-gateway》。

附上:

博文实例demo:https://github.com/sunmi-OS/grpc-gateway-demo

grpc-gateway官网:https://github.com/grpc-ecosystem/grpc-gateway

一,grpc-gateway介绍

grpc-gateway是protoc的一个插件 。它读取Grpc服务定义,并生成反向代理服务器,将RESTful JSON API请求转换为Grpc的方式调用。主要是根据 google.api.http定义中思想完成的,一下就是grpc-gateway结构图:

Go Grpc Gateway兼容HTTP协议文档自动生成网关

二,grpc-gateway环境准备

grpc-gateway使用完全的Go语言进行开发,所以安装起来也非常简单,首先需要获取相关的依赖包

PS:需要先准备好准备好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
cd $GOPATH/src/
mkdir -p grpc-gateway-demo/gateway
cd grpc-gateway-demo/gateway
vim gateway.proto
syntax = "proto3";
package gateway;
# 新增以下引入
import "google/api/annotations.proto";
message StringMessage {
    string value = 1;
}
# 修改方法增加http定义
# service Gateway {
#   rpc SayHello Echo(StringMessage) returns (StringMessage) {}
# }
service Gateway {
   rpc Echo(StringMessage) returns (StringMessage) {
       option (google.api.http) = {
           post: "/v1/example/echo"
           body: "*"
       };
   }
}

生成grpc结构文件和gateway文件:

protoc --proto_path=../ -I/usr/local/include -I. -I$GOPATH/src -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=plugins=grpc:. gateway.proto

protoc --proto_path=../ -I/usr/local/include -I. -I$GOPATH/src -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true:. gateway.proto

最终可以看到以下文件

Go Grpc Gateway兼容HTTP协议文档自动生成网关

二,编写grpc-gateway服务

服务端代码:

cd ..
vim grpc_service.go
package main
import (
    "log"
    "net"
    pb "grpc-gateway-demo/gateway"
    "google.golang.org/grpc"
    "golang.org/x/net/context"
)
const (
    PORT = ":9192"
)
type server struct {}
func (s *server) Echo(ctx context.Context, in *pb.StringMessage) (*pb.StringMessage, error) {
    log.Println("request: ", in.Value)
    return &pb.StringMessage{Value: "Hello " + in.Value}, nil
}
func main() {
    lis, err := net.Listen("tcp", PORT)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGatewayServer(s, &server{})
    log.Println("rpc服务已经开启")
    s.Serve(lis)
}

运行grpc服务端:

go build grpc_service.go
./grpc_service

Go Grpc Gateway兼容HTTP协议文档自动生成网关

编写gateway服务

vim grpc_gateway.go
package main
import (
    "flag"
    "net/http"
    "log"
    "github.com/golang/glog"
    "golang.org/x/net/context"
    "github.com/grpc-ecosystem/grpc-gateway/runtime"
    "google.golang.org/grpc"
    gw "grpc-gateway-demo/gateway"
)
var (
    echoEndpoint = flag.String("echo_endpoint", "localhost:9192", "endpoint of Gateway")
)
func run() error {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()
    mux := runtime.NewServeMux()
    opts := []grpc.DialOption{grpc.WithInsecure()}
    err := gw.RegisterGatewayHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts)
    if err != nil {
        return err
    }
    log.Println("服务开启")
    return http.ListenAndServe(":8080", mux)
}
func main() {
    flag.Parse()
    defer glog.Flush()
    if err := run(); err != nil {
        glog.Fatal(err)
    }
}

运行网关程序

go build grpc_gateway.go
./grpc_gateway

Go Grpc Gateway兼容HTTP协议文档自动生成网关

使用http的方式调用网关:

curl -X POST -k http://localhost:8080/v1/example/echo -d '{"value":" world"}'
{"value":"Hello  world"}

四,使用gateway生成swagger文档

cd gateway
protoc -I/usr/local/include -I. \
  -I$GOPATH/src \
  -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
  --swagger_out=logtostderr=true:. \
  gateway.proto

Go Grpc Gateway兼容HTTP协议文档自动生成网关

五,性能对比

对比以下两项:

http -> go -> grpc -> go

http -> go -> http -> grpc_gateway -> grpc -> go

全程使用ab 带 -k进行压测

http -> go -> grpc -> go

Go Grpc Gateway兼容HTTP协议文档自动生成网关

Go Grpc Gateway兼容HTTP协议文档自动生成网关

http -> go -> http -> grpc_gateway -> grpc -> go

Go Grpc Gateway兼容HTTP协议文档自动生成网关

Go Grpc Gateway兼容HTTP协议文档自动生成网关

六,总结

在GO的场景下基本上4倍差距,但是考虑到本身Go在grpc和http上本身就有3.5倍的差距,本身在同等HTTP的情况下经过grpc-gateway和不经过直接到API差距大概在20~30%左右,这样的性能消耗带来的是兼容HTTP并且还可以自动生成swagger(还可以作为调试工具),何乐而不为呢?

以上就是Go Grpc Gateway兼容HTTP协议文档自动生成网关的详细内容,更多关于Go Grpc Gateway兼容HTTP的资料请关注三水点靠木其它相关文章!


Tags in this post...

Golang 相关文章推荐
一文读懂go中semaphore(信号量)源码
Apr 03 Golang
Go缓冲channel和非缓冲channel的区别说明
Apr 25 Golang
Golang 正则匹配效率详解
Apr 25 Golang
关于golang高并发的实现与注意事项说明
May 08 Golang
golang 实现并发求和
May 08 Golang
聊聊golang中多个defer的执行顺序
May 08 Golang
Go语言实现Snowflake雪花算法
Jun 08 Golang
使用GO语言实现Mysql数据库CURD的简单示例
Aug 07 Golang
Go归并排序算法的实现方法
Apr 06 Golang
golang三种设计模式之简单工厂、方法工厂和抽象工厂
Apr 10 Golang
Go语言 详解net的tcp服务
Apr 14 Golang
Go gorilla securecookie库的安装使用详解
Aug 14 Golang
Go gRPC进阶教程gRPC转换HTTP
Jun 16 #Golang
GoFrame gredis缓存DoVar Conn连接对象 自动序列化GoFrame gredisDo/DoVar方法Conn连接对象自动序列化/反序列化总结
Jun 14 #Golang
Go调用Rust方法及外部函数接口前置
详解Go语言中配置文件使用与日志配置
Jun 01 #Golang
详解Go语言中Get/Post请求测试
Golang实现可重入锁的示例代码
May 25 #Golang
Go web入门Go pongo2模板引擎
May 20 #Golang
You might like
2019年中国咖啡业现状与发展趋势
2021/03/04 咖啡文化
php数组总结篇(一)
2008/09/30 PHP
PHP+Mysql树型结构(无限分类)数据库设计的2种方式实例
2014/07/15 PHP
Linux中为php配置伪静态
2014/12/17 PHP
PHP中for循环与foreach的区别
2017/03/06 PHP
PHP中strtr与str_replace函数运行性能简单测试示例
2019/06/22 PHP
SharePoint 客户端对象模型 (一) ECMA Script
2011/05/22 Javascript
jquery异步跨域访问代码
2013/06/28 Javascript
Js判断CSS文件加载完毕的具体实现
2014/01/17 Javascript
javascript学习笔记--数字格式类型
2014/05/22 Javascript
原生JS实现匀速图片轮播动画
2016/10/18 Javascript
详解nodejs 文本操作模块-fs模块(四)
2016/12/22 NodeJs
jQuery插件zTree实现清空选中第一个节点所有子节点的方法
2017/03/08 Javascript
纯js的右下角弹窗实例
2017/03/12 Javascript
微信小程序-getUserInfo回调的实例详解
2017/10/27 Javascript
p5.js入门教程之键盘交互
2018/03/19 Javascript
jQuery实现的上传图片本地预览效果简单示例
2018/03/29 jQuery
node前端开发模板引擎Jade的入门
2018/05/11 Javascript
webpack 处理CSS资源的实现
2019/09/27 Javascript
python正则表达式修复网站文章字体不统一的解决方法
2013/02/21 Python
Python制作CSDN免积分下载器
2015/03/10 Python
python中使用zip函数出现错误的原因
2018/09/28 Python
python贪吃蛇游戏代码
2020/04/18 Python
Python----数据预处理代码实例
2019/03/20 Python
详解Python 循环嵌套
2020/07/09 Python
通过代码实例了解Python异常本质
2020/09/16 Python
美国知名的百货清仓店:Neiman Marcus Last Call
2016/08/03 全球购物
台湾良兴购物网:EcLife
2019/12/01 全球购物
查环查孕证明
2014/01/10 职场文书
车辆工程专业求职信
2014/06/14 职场文书
体育课外活动总结
2014/07/08 职场文书
初中毕业典礼演讲稿
2014/09/09 职场文书
爱心募捐感谢信
2015/01/22 职场文书
旗帜观后感
2015/06/08 职场文书
2016秋季田径运动会广播稿
2015/12/21 职场文书
一文搞清楚MySQL count(*)、count(1)、count(col)区别
2022/03/03 MySQL