grpc提供http訪問方式

0x00

最近系統在從c++遷移到go,之前使用brpc,也需要轉移到grpc,但是grpc提供的接口服務原生無法被http訪問到,這對我們調試來說也很麻煩,所以需要讓grpcbrpc一樣,http也能訪問rpc接口

0x01

grpc-gateway項目:

該項目是在grpc外面加一層反向代理,由代理服務器轉發json格式,轉變成protobuf格式來訪問grpc服務,官方解釋圖如下:

你的grpc服務按照正常的方式啓動就行了,然後根據proto文件生成gateway專有的gw.pb.go文件,然後我們重新啓動一個gateway服務,有自己獨立的端口,然後有一個入口,入口就是你grpc提供服務的ip和端口。

實驗

啓動grpc服務

這裏寫圖片描述

grpc提供服務的端口爲7777

啓動代理服務

package main

import (
	"flag"
	"github.com/golang/glog"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"net/http"

	gw "data/proto"
)

var (
	echoEndPoint = flag.String("echo_endpoint", "localhost:7777", "endpoint of YourService")
)

func run() error {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}
	err := gw.RegisterGreeterHandlerFromEndpoint(ctx, mux, *echoEndPoint, opts)
	if err != nil {
		return err
	}

	return http.ListenAndServe(":8989", mux)

}

func main() {
	flag.Parse()
	defer glog.Flush()

	if err := run(); err != nil {
		glog.Fatal(err)
	}
}

gateway的端口爲8989endpoint指向了grpc服務的端口7777

postman訪問

這裏寫圖片描述

訪問成功

缺點

  • 需要開2個端口
  • 寫多餘的代碼

理想情況下應該有個插件自己把http請求轉換成proto的方式,猶如brpc一樣

解決方法

後來發現https的方式是可以解決上面的問題,grpc和https端口在一起,也不用起兩個服務。

grpc https gateway

20190621更新

同事用https://github.com/soheilhy/cmux把多個協議的服務都綁定到一起了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章