快速开始
最后更新于:2022-04-02 02:49:09
[TOC]
## 概述
推荐使用 micro 最新版(v4)
## 安装 micro
获取 micro 命令
```
go install go-micro.dev/v4/cmd/micro@master
```
> Version`1.16`or higher
## 初始化项目
1. 初始化项目
```
micro new service helloworld
cd helloworld
make init
make proto tidy
```
如果想把proto 生成的代码放到目录下可先进行如下修改,在执行 `make proto`
```
option go_package = "./protoc;hello";
// 改为
option go_package = "./proto/hello;hello";
```
4. 运行 micro server
```
micro server
```
5. 运行当前程序
```
micro run .
```
6. 查看状态
```
micro status
```
## 添加组件
### 添加配置中心 [service 层/Api 层]
1. 开启 consul
```
docker run -d --name consul -p 8500:8500 consul
```
2. 获取consul的模块
```
go get github.com/asim/go-micro/plugins/config/source/consul/v4
```
3. 添加配置中心
```
// common.go
func GetConsulConfig(host string,port int64,prefix string)(config.Config,error) {
source := consul.NewSource(
consul.WithAddress(host+":"+strconv.FormatInt(port, 10)),
consul.WithPrefix(prefix),
consul.StripPrefix(true),
)
newConfig, err := config.NewConfig()
if err != nil {
return nil,err
}
err = newConfig.Load(source)
if err != nil {
return nil,err
}
return newConfig,nil
}
// mysql.go
func GetMysqlFromConsul(config config.Config,path ...string)*MysqlConfig{
mysqlConfig:=&MysqlConfig{}
config.Get(path...).Scan(mysqlConfig)
return mysqlConfig
}
// main.go
consulConfig, err := common.GetConsulConfig("127.0.0.1", 8500, "/micro/config")
if err != nil {
log.Fatalln(err)
}
// 读取配置的两种方式
// 方式一:直接从consul获取mysql 配置,从 consul 中获取mysql的配置信息
mysqlInfo :=common.GetMysqlFromConsul(consulConfig,"mysql")
// 方式二: 从 注册的微服务中获取,前提是必须注册成 micro.Config(consulConfig),
mysqlInfo :=common.GetMysqlFromConsul(srv.Options().Config,"mysql")
```
### 添加注册中心 [service 层/Api 层]
1. 获取go mod
```
github.com/asim/go-micro/plugins/registry/consul/v4
```
2. 添加当前服务到注册中心
```
// 注册 consul 成服务需要的consul 服务地址
consulRegistry:=consul.NewRegistry(func(opts *registry.Options) {
opts.Addrs=[]string{
"127.0.0.1:8500",
}
})
// Create service
srv := micro.NewService(
micro.Name("category.service"),
micro.Version("latest"),
micro.Address("127.0.0.1:8082"), // 指定此服务的端口
micro.Registry(consulRegistry), // 把 micro 注册到 consul
)
```
3. 客户端访问
```
// 配置注册中心就可以访问配置中心
consulRegistry:=consul.NewRegistry(func(opts *registry.Options) {
opts.Addrs=[]string{
"127.0.0.1:8500",
}
})
service := micro.NewService(
micro.Name("category.client"),
micro.Version("latest"),
micro.Registry(consulRegistry),
)
service.Init()
categoryService := category.NewCategoryService("category.service", service.Client())
```
### 添加链路追踪 [service 层/Api 层]
common/jaeger.go
```func NewTracer(serverName string,addr string)(opentracing.Tracer,io.Closer,error){
conf := &config.Configuration{
ServiceName: serverName,
Sampler: &config.SamplerConfig{
Type: jaeger.SamplerTypeConst,
Param: 1,
},
Reporter: &config.ReporterConfig{
BufferFlushInterval: 1*time.Second,
LogSpans: true,
LocalAgentHostPort: addr,
},
}
tracer, closer, err := conf.NewTracer()
return tracer,closer,err
}
```
**服务层的main.go**
```
tracer, closer, err := common.NewTracer("go.micro.api.cartApi", "127.0.0.1:831")
if err != nil {
log.Error(err)
}
defer closer.Close()
opentracing.SetGlobalTracer(tracer) // "github.com/opentracing/opentracing-go"
srv := micro.NewService(
micro.Name(service),
micro.Version(version),
micro.Address(addr),
...
// 链路追踪
// 因为是以客户端的形式访问,
// WrapHandler -> WrapClient
micro.WrapHandler(
opentracing2.NewHandlerWrapper(opentracing.GlobalTracer()),
),
)
...
```
**API层的main.go**
```
tracer, closer, err := common.NewTracer("go.micro.api.cartApi", "127.0.0.1:831")
if err != nil {
log.Error(err)
}
defer closer.Close()
opentracing.SetGlobalTracer(tracer) // "github.com/opentracing/opentracing-go"
srv := micro.NewService(
micro.Name(service),
micro.Version(version),
micro.Address(addr),
...
// 链路追踪
// 因为是以客户端的形式访问,
// WrapHandler -> WrapClient
micro.WrapClient(
opentracing2.NewClientWrapper(opentracing.GlobalTracer()),
),
)
...
```
### 添加限流 [service 层]
**服务层的main.go**
```
srv := micro.NewService(
micro.Name("cart.server"),
micro.WrapHandler(
// 添加限流
ratelimit.NewHandlerWrapper(QPS),
),
)
srv.Init()
```
### 添加负责均衡 [Api 层]
main.go
```
srv := micro.NewService(
micro.Name(service),
// 添加负责均衡
micro.WrapClient(roundrobin.NewClientWrapper()),
)
srv.Init()
```
### 添加熔断 [Api 层]
main.go
```
//熔断器
hystrixHandler := hystrix.NewStreamHandler() // github.com/afex/hystrix-go/hystrix
hystrixHandler.Start()
// 启动端口
go func() {
err := http.ListenAndServe(net.JoinHostPort("0.0.0.0", "9096"),
hystrixHandler)
if err != nil {
log.Error(err)
}
}()
srv := micro.NewService(
micro.Name(service),
...
// 添加熔断 micro v4 可以直接添加
micro.WrapClient(hystrix2.NewClientWrapper()),
)
srv.Init()
```
';