🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[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() ``` #### 添加 prometheus [参考](https://segmentfault.com/a/1190000023530052) 1. mciro 中添加 prometheus ``` import ( "net/http" "github.com/micro/go-plugins/wrapper/monitoring/prometheus/v2" "github.com/prometheus/client_golang/prometheus/promhttp" //... ) func main(){ // ... service := micro.NewService( micro.Name("go.micro.api.myauth"), micro.Version("latest"), micro.WrapHandler(prometheus.NewHandlerWrapper()), ) // ... } func PrometheusBoot() { http.Handle("/metrics", promhttp.Handler()) // 启动web服务,监听8085端口 go func() { err := http.ListenAndServe("localhost:8085", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }( ``` 2. 启动prometheus prometheus.yml ``` global: scrape_interval: 15s # By default, scrape targets every 15 seconds. # Attach these labels to any time series or alerts when communicating with # external systems (federation, remote storage, Alertmanager). external_labels: monitor: 'codelab-monitor' # A scrape configuration containing exactly one endpoint to scrape: # Here it's Prometheus itself. scrape_configs: # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config. - job_name: 'prometheus' # Override the global default and scrape targets from this job every 5 seconds. scrape_interval: 5s static_configs: - targets: ['192.168.0.110:8085'] ``` 启动 ``` docker run -d -p 9090:9090 -v prometheus.yml:/etc/prometheus/prometheus.yml --name p`rometheus prom/prometheus ``` 访问 ``` http://localhost:9090/ ``` 3. 启动grafana ``` docker run -d -p 3000:3000 grafana/grafana ``` 首先设置数据源,选择prometheus,url填http://宿主ip:9090/ ,点击保存,提示成功即可 ![](https://img.kancloud.cn/72/a7/72a756ff77c556463d18a0103520df57_732x418.png) ashboard中点击`add panel`, 选择数据源,填写metrics(点击有提示),完成后点`apply`即可