首页 > 其他分享 >【转】五分钟给你的 gRPC服务 加上 HTTP 接口

【转】五分钟给你的 gRPC服务 加上 HTTP 接口

时间:2023-04-09 23:45:24浏览次数:57  
标签:HTTP proto gRPC sum pb 五分钟 go gateway

 

原文:https://www.cnblogs.com/kevinwan/p/16492868.html

-------------------------------

gRPC 服务要加 HTTP 接口?

go-zero 给大家带来极简的 RESTful 和 gRPC 服务开发体验的同时,社区又给我们提出了新的期望:

  • 我想只写一次代码
  • 既要 gRPC 接口
  • 也要 HTTP 接口
  • 既要。。。也要。。。

也有道理嘛!你看用户怎么说:

用户A:一套逻辑,api和rpc一起

用户B:go-zero要是能简化这一步我感觉会成为go生态中最好的微服务框架没有之一

于是,我陷入了深深的思考:用户从来是不会错的,但是我们要不要提供呢?

于是,你看到了这篇文章。。。

我们先提供 gRPC 服务

对于这种服务,我们太熟了。新建一个目录,就叫 grpc-restufl 吧,里面放个 sum.proto 文件

syntax = "proto3";

package sum;
option go_package="./pb";

message Numbers {
    int64 a = 1;
    int64 b = 2;
}

message SumRequest {
    Numbers numbers =1;
}

message SumResponse {
    int64 result = 1;
}

service Sum {
    rpc Add(SumRequest) returns (SumResponse) {}
}

一键生成,你懂的。。。

$ goctl rpc protoc --go_out=. --go-grpc_out=. --zrpc_out=. sum.proto

看看都有了啥

.
├── etc
│   └── sum.yaml
├── go.mod
├── internal
│   ├── config
│   │   └── config.go
│   ├── logic
│   │   └── addlogic.go
│   ├── server
│   │   └── sumserver.go
│   └── svc
│       └── servicecontext.go
├── pb
│   ├── sum.pb.go
│   └── sum_grpc.pb.go
├── sum
│   └── sum.go
├── sum.go
└── sum.proto

实现一下业务逻辑,将 internal/logic/addlogic.go 里的 Add 方法修改如下:

func (l *AddLogic) Add(in *pb.SumRequest) (*pb.SumResponse, error) {
    return &pb.SumResponse{
        Result: in.Numbers.A+in.Numbers.B,
    }, nil
}

可以跑了,业务逻辑也是有了的(虽然很简单,演示嘛。。。)

$ go mod tidy && go run sum.go
Starting rpc server at 127.0.0.1:8080...

对于熟悉 go-zero 的同学来说,至此无亮点(新知识),接下来 GET 新技能~

提供 HTTP 接口

更新 go-zero

首先,我们更新 go-zero 至 master 版,因为 gateway 还没正式发版,八月初会正式跟大家见面

$ go get -u github.com/zeromicro/go-zero@master

修改 proto 文件

修改 sum.proto,我新建了一个 sum-api.proto,如下:

syntax = "proto3";

package sum;
option go_package="./pb";

import "google/api/annotations.proto";

message Numbers {
    int64 a = 1;
    int64 b = 2;
}

message SumRequest {
    Numbers numbers =1;
}

message SumResponse {
    int64 result = 1;
}

service Sum {
    rpc Add(SumRequest) returns (SumResponse) {
        option (google.api.http) = {
            post: "/v1/sum"
            body: "*"
        };
    }
}

生成 proto descriptor 文件

protoc --include_imports --proto_path=. --descriptor_set_out=sum.pb sum-api.proto

修改配置文件

修改后的 internal/config/config.go 如下(部分):

type Config struct {
    zrpc.RpcServerConf
    Gateway gateway.GatewayConf
}

修改后的 etc/sum.yaml 如下:

Gateway:
  Name: gateway
  Port: 8081
  Upstreams:
    - Grpc:
        Endpoints:
          - localhost:8080
      ProtoSet: sum.pb

修改 main 函数

创建 gateway 并用 ServiceGroup 来管理 gRPC server 和 gateway server,部分代码如下:

    gw := gateway.MustNewServer(c.Gateway)
    group := service.NewServiceGroup()
    group.Add(s)
    group.Add(gw)
    defer group.Stop()

    fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
    fmt.Printf("Starting gateway at %s:%d...\n", c.Gateway.Host, c.Gateway.Port)
    group.Start()

大功告成

让我们来启动服务

$ go run sum.go
Starting rpc server at 127.0.0.1:8080...
Starting gateway at 0.0.0.0:8081...

用 curl 测试一下

$ curl -i -H "Content-Type: application/json" -d '{"numbers":{"a":2,"b":3}}' localhost:8081/v1/sum
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Traceparent: 00-ad5b7df7a834a1c05ee64999e3310811-195ba1f4f9956cc4-00
Date: Mon, 18 Jul 2022 14:33:11 GMT
Content-Length: 20

{
  "result": "5"
}

再看我们的 gateway 和 gRPC 的日志里的链路信息和客户端收到的都能对应上,赞!

{"@timestamp":"2022-07-18T22:33:11.437+08:00","caller":"serverinterceptors/statinterceptor.go:76","content":"127.0.0.1:61635 - /sum.Sum/Add - {\"numbers\":{\"a\":2,\"b\":3}}","duration":"0.0ms","level":"info","span":"b3c85cd32a76f8c9","trace":"ad5b7df7a834a1c05ee64999e3310811"}
{"@timestamp":"2022-07-18T22:33:11.438+08:00","caller":"handler/loghandler.go:197","content":"[HTTP] 200 - POST /v1/sum - 127.0.0.1:61662 - curl/7.79.1","duration":"0.7ms","level":"info","span":"195ba1f4f9956cc4","trace":"ad5b7df7a834a1c05ee64999e3310811"}

结束语

你看,给我们的 gRPC 服务加上 HTTP 接口是不是五分钟就可以完成了?是不是?

另外,不要小看这个简单的 gateway,配置里如果是对接后面的 gRPC 服务发现的话,会自动负载均衡的,并且还可以自定义中间件,想怎么控制就怎么控制。

是不是有点心动了呢?

对了,这个示例的完整代码在:

https://github.com/kevwan/grpc-restful

项目地址

https://github.com/zeromicro/go-zero

欢迎使用 go-zero 并 star 支持我们!

微信交流群

关注『微服务实践』公众号并点击 交流群 获取社区群二维码。

标签:HTTP,proto,gRPC,sum,pb,五分钟,go,gateway
From: https://www.cnblogs.com/oxspirt/p/17301471.html

相关文章

  • HTTP/HTTPS/HTTP2
    HTTP协议图文简述--HTTP/HTTPS/HTTP2 01、准备1.1、先了解下网络模型/TCPHTTP 连接是建立在 TCP*协议之上的,其数据传输功能是由TCP完成的,那TCP又是什么呢?TCP 是一个单纯用来建立通信连接,并传输数据的基础协议,属于网络模型中的的传输层。OSI模型(OpenSystemInterc......
  • SpringSecurity之WebSecurity和HttpSecurity
    SpringSecurity启动过程中有两个重要的类。分别是WebSecurity和HttpSecurity。 看看WebSecurity的定义:publicfinalclassWebSecurityextendsAbstractConfiguredSecurityBuilder<Filter,WebSecurity>implementsSecurityBuilder<Filter>,ApplicationContextAware,Servl......
  • http协议学习
    既然学习web,就少不了HTTP协议,以下是我对此的一些总结1、概念:客户端连上web服务器后,若想获得web服务器中的某个web资源,需遵守一定的通讯格式,HTTP协议用于定义客户端与web服务器通迅的格式(规定客户端和服务器如何进行交互)。HTTP是hypertexttransferprotocol(超文本传输协议)的简......
  • 23.04.06_为博客设置https
    title:为博客设置https协议categories: -博客优化date:2023-04-06url_dir:Blog_optimizationurl_name:setting_https博客优化内容http协议的网站总是显示不安全,为了开启小绿锁,在这里准备部署https协议。我的博客是hexo架构,部署在阿里云上的。在阿里云首页中选择产......
  • BlackLotus 分析3--http_downloader
    目录BlackLotus分析3--http_downloaderstartinit_ntdll_apiinit_other_apicommunication_140004804msftncsi_140003FD4getinfo_140005DFCisUEFISecureBootEnabled_140005CB4get_HWID_MAC_VolumeSerialNumber_md5wstrget_RegisteredOwner_data_140006238get_publicip_1400059FCget......
  • OKHttp库都用到了哪些设计模式
    Builder模式:用于构建OkHttpClient、Request和Response等类的对象,以实现链式调用和可配置性。Singleton模式:用于创建OkHttpClient和Dispatcher等类的单例对象,以确保全局只有一个实例。Factory模式:用于创建Call和WebSocket等类的对象,以隐藏对象的创建细节并提供灵活性。C......
  • Apache httpd 入门实战(1)--概念及安装
    Apachehttpd是Apache软件基金会的一个开源的Web服务器,可以在大多数计算机操作系统中运行,由于其跨平台和安全性被广泛使用,是最流行的Web服务器端软件之一。本文主要介绍其基本概念及安装,文中所使用到的软件版本:httpd2.4.55、apr1.7.2、apr-util1.6.3、pcre8.43、CentOS......
  • HTTP接口风格就俩:RPC和RESTFul
    基于.NetCore开发博客项目StarBlog-(21)开始开发RESTFul接口 前言最近电脑坏了,开源项目的进度也受到一些影响这篇酝酿很久了,作为本系列第二部分(API接口开发)的第一篇,得想一个好的开头,想着想着就鸽了好久,索性不扯那么多了,直接开写吧~关于RESTFul网上很多相关的文章都要......
  • SAP ABAP 中,if_http_extension 接口的flow_rc 字段含义
    我们在SAPABAPGateway系统的框架实现代码,/iwfnd/cl_sodata_http_handler的handle_request方法里,能看到代码第55行对if_http_extension这个接口的属性字段flow_rc进行赋值。在SAPABAP中,if_http_extension接口是用于处理HTTP请求和响应的标准接口。其中,flow_r......
  • SAP ABAP Gateway 系统里 HTTP 请求响应头部字段 DataServiceVersion 的可能取值范围
    SAPABAPGateway系统里HTTP请求的响应头部字段集合里,DataServiceVersion这个字段的作用是什么,包含哪些可能的值?如下图第178行代码所示。在SAPABAPGateway系统中,DataServiceVersion是HTTP响应头部字段集合中的一个字段,用于指定OData服务的版本信息。具体来说,Da......