GO-Grpc微服務開發一 服務編寫
阿新 • • 發佈:2018-12-20
服務編寫
1.定義proto檔案
//示例為elc日誌 syntax = "proto3"; //service name is kibana service Kibana { //service method is write rpc Write(WriteRequest) returns (WriteResponse) {} } //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; }
2.將定義的proto編譯為go檔案
protoc --proto_path=.:. --micro_out=. --go_out=. kibana.proto
3.編寫服務
package main import ( proto "micro-srv/service/kibana/proto" "micro-srv/service/kibana/logics" "fmt" "micro-srv/common" "golang.org/x/net/context" ) type Kibana struct{} const ( SRV_PORT = 50061 SRV_NAME = "kibana" ) func (k *Kibana) Write(ctx context.Context, req *proto.WriteRequest) (rsp *proto.WriteResponse, err error) { rsp.Code = 0 rsp.Message = "success" rsp.Data = map[string]string{"tag":req.Tag,"info":req.Info,"level":req.Level} err = logics.WriteLog(req.Tag, req.Info, req.Level) return rsp, err } func main() { server, listener, err := common.Register(SRV_NAME, SRV_PORT) if err != nil { fmt.Println(err.Error()) } proto.RegisterKibanaServer(server, &Kibana{}) err = server.Serve(listener) if err != nil { fmt.Println(err.Error()) } }
微服務執行 (本地環境示例)
啟動consul
consul agent -dev &
啟動並註冊服務
cd kibana && go run main.go &