GO-Grpc微服务开发六 网关和http调用
GO-Grpc微服务开发六 网关和http调用proto文件定义将定义的proto编译为go文件网关中注册服务http请求proto文件定义syntax = "proto3";package kibana;//引入google api实现http转rpcimport "google/api/annotations.proto";//service name
·
GO-Grpc微服务开发六 网关和http调用
proto文件定义
syntax = "proto3";
package kibana;
//引入google api实现http转rpc
import "google/api/annotations.proto";
//service name is kibana
service Kibana {
//service method is write
rpc Write(WriteRequest) returns (WriteResponse) {
//定义http请求路由
option (google.api.http) = {
//路由
post: "/v1/kibana/write"
//参数为 request body
body: "*"
};
}
}
//writer request struct
message WriteRequest {
string tag = 1;
string info = 2;
string level = 3;
}
//writer response struct
message WriteResponse {
int32 code = 1;
string message = 2;
map<string, string> data = 3;
}
将定义的proto编译为go文件
//生成grpc文件
protoc --go_out=plugins=grpc:. kibana.proto
//生成网关文件
//注意点:请先将google/api下载到/usr/local/include
protoc -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:. kibana.proto
网关中注册服务
package main
import (
"github.com/golang/glog"
"golang.org/x/net/context"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
"net/http"
//引入刚生产的文件包 多个服务引入多个包
kibana "micro-srv/service/kibana/proto"
"micro-srv/common"
"fmt"
)
var services = map[string]string{
//这里加上我们的服务
"kibana": "50061",
}
func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
mux := runtime.NewServeMux()
base := common.Common{}
//获取服务地址
server_host := base.GetVal("serveraddr")
//注册http转grpc服务
registerServerHandle(ctx, mux, server_host)
return http.ListenAndServe(":8080", mux)
}
//注册http转grpc服务
func registerServerHandle(ctx context.Context, mux *runtime.ServeMux, server_host string) {
opts := []grpc.DialOption{grpc.WithInsecure()}
var err error
//注册服务 kibana 多个服务多次注册即可
err = kibana.RegisterKibanaHandlerFromEndpoint(ctx, mux, server_host + ":" + services["kibana"], opts)
if err != nil {
fmt.Printf("kibana http is fail: %s", err.Error())
}
}
func main() {
defer glog.Flush()
if err := run(); err != nil {
glog.Fatal(err)
}
}
http请求
- 确保网关中已注册服务
- 确保网关和服务已运行
curl
curl -H "Content-Type:application/json" -X POST --data '{"tag":"micro_test", "info":"hello", "level":"info"}' http://127.0.0.1:5061/v1/kibana/write
beego
url := "http://127.0.0.1:5061/v1/kibana/write"
params := map[string]string{
"tag": "micro_test",
"info": "hello",
"level": "info",
}
req := httplib.Post(url)
req.JSONBody(params)
con, err := req.Bytes()
更多推荐
已为社区贡献1条内容
所有评论(0)