zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Golang gRPC 和 gRPC-gateway 结合使用

gatewayGolang 结合 grpc 使用
2023-09-27 14:29:03 时间

一、安装

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

二、proto 文件

syntax = "proto3";
package gateway;

import "google/api/annotations.proto";

message StringMessage {
    string value = 1;
}

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

执行 protoc 编译,生成两个 go 文件,一个是提供 service 的,一个是 gateway 的:

protoc --proto_path=../ -I/usr/local/include -I. -I/home/go-plugin/src -I/home/go-plugin/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/home/go-plugin/src -I/home/go-plugin/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true:. gateway.proto

 生成的文件如下:

第一个是 service,第二个是 gateway

三、编写 go 程序

1、service

package main

import (
    "log"
    "net"

    pb "test_grpc/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)
}
View Code

2、gateway

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 "test_grpc/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)
    }
}
View Code

四、开启服务

先开启 service,再开启 gateway