0%

Golang 微服务框架系列 - 3, 使用 Micro 框架生成并编译运行第一个 srv 服务

Micro 介绍

官方网站: micro.mu
官方文档: micro.mu/docs
源码仓库: github.com/micro/micro

Micro 是一个工具集合, 通过将微服务架构抽象成一组工具。隐藏了分布式系统的复杂性,为开发人员提供了更简洁的概念。

通过 micro 创建项目:

1
2
3
4
micro new --type "srv" \
--namespace "com.test" \
--alias "first_srv" \
github.com/micro/examples/first_srv

命令会生成一个 工程目录, 包含了一些通用代码, 目录结构:

1
2
3
4
5
6
7
8
9
10
11
├── main.go
├── plugin.go
├── handler
│ └── example.go
├── subscriber
│ └── example.go
├── proto\example
│ └── example.proto
├── Dockerfile
├── Makefile
└── README.md

安装 protobuf:

  1. https://github.com/google/protobuf/releases 下载对应平台的 protobuf 包
  2. 把 bin目录添加到 PATH 环境变量中.
  3. 在命令行中运行 protoc , 如果提示命令未找到检查 protobuf 是否安装成功.

安装 protobuf 代码生成相关库:

1
2
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
go get -u github.com/micro/protoc-gen-micro

通过 proto 文件生成 go 代码:

1
2
cd $GOPATH\src\github.com\micro\examples\first_srv
protoc --go_out=. --micro_out=. proto/example/example.proto

运行:

1
2
3
4
$ go build github.com/micro/examples/first_srv && first_srv
2018/06/17 13:26:13 Listening on [::]:9040
2018/06/17 13:26:13 Broker Listening on [::]:9041
2018/06/17 13:26:13 Registering node: com.test.srv.first_srv-f325ad49-71ee-11e8-a4a2-7054d2dea53d

由于使用的是服务发现,所以上面打印的端口在你机器上可能不一样,因为端口是随机的,但不影响正常运行.

验证是否成功

  • 获取服务列表
1
2
3
4
$ micro list services
com.test.srv.first_srv
consul
topic:com.test.srv.first_srv
  • 获取服务详情
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
$ micro get service com.test.srv.first_srv
service com.test.srv.first_srv

version latest

ID Address Port Metadata
com.test.srv.first_srv-f325ad49-71ee-11e8-a4a2-7054d2dea53d 192.168.0.106 9040 transport=http,broker=http,server=rpc,registry=consul

Endpoint: Example.Call
Metadata: stream=false

Request: {
name string
-
- []uint8 {
uint8 uint8
}
- int32
}

Response: {
msg string
-
- []uint8 {
uint8 uint8
}
- int32
}


Endpoint: Example.PingPong
Metadata: stream=true

Request: {}

Response: {}


Endpoint: Example.Stream
Metadata: stream=true

Request: {}

Response: {}


Endpoint: Example.Handle
Metadata: subscriber=true,topic=com.test.srv.first_srv

Request: {
say string
-
- []uint8 {
uint8 uint8
}
- int32
}

Response: {}


Endpoint: Func
Metadata: subscriber=true,topic=com.test.srv.first_srv

Request: {
say string
-
- []uint8 {
uint8 uint8
}
- int32
}

Response: {}
  • 尝试调用服务
1
2
3
4
5
$ micro query com.test.srv.first_srv Example.Call '{"name":"My_name"}'
Deprecated. Use call instead
{
"msg": "Hello My_name"
}