0x00
最近系統在從c++
遷移到go
,之前使用brpc
,也需要轉移到grpc
,但是grpc
提供的接口服務原生無法被http
訪問到,這對我們調試來說也很麻煩,所以需要讓grpc
跟brpc
一樣,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
的端口爲8989
,endpoint
指向了grpc
服務的端口7777
。
postman訪問
訪問成功
缺點
- 需要開2個端口
- 寫多餘的代碼
理想情況下應該有個插件自己把http
請求轉換成proto
的方式,猶如brpc
一樣
解決方法
後來發現https的方式是可以解決上面的問題,grpc和https端口在一起,也不用起兩個服務。
20190621更新
同事用https://github.com/soheilhy/cmux把多個協議的服務都綁定到一起了