# 服务编写
## 1.定义proto文件
```$xslt
//示例为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文件
```$xslt
protoc --proto_path=.:. --micro_out=. --go_out=. kibana.proto
```
## 3.编写服务
```$xslt
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 &`
![在这里插入图片描述](https://img-blog.csdnimg.cn/20181108101858914.png)
可以看到我们服务以及运行起来了
接下来我们在consul面板看看
![在这里插入图片描述](https://img-blog.csdnimg.cn/20181108101816935.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzE4MzQ3NQ==,size_16,color_FFFFFF,t_70)
源码:[go-grpc-getway](https://github.com/juelite/micro-srv)
有疑问加站长微信联系(非本文作者))