转载

GO-Grpc微服务开发二 服务编写

服务编写

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() {
	//将服务注册到consul
    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 &

面板地址:http://127.0.0.1:8500

启动并注册服务

cd kibana && go run main.go & GO-Grpc微服务开发二 服务编写

可以看到我们服务以及运行起来了 接下来我们在consul面板看看 GO-Grpc微服务开发二 服务编写

源码: go-grpc-getway

原文  https://studygolang.com/articles/17231
正文到此结束
Loading...