go micro registry 插件consul

go micro v2版本中,consul不在默認支持,官方推薦使用etcd,具體緣由官方blog有講https://medium.com/microhq/de...git

consul被放到go-plugins, 由社區維護github.com/micro/go-plugins/registry/consulgithub

要使用consul,須要從go-plugins引入web

import (
    "fmt"
    "os"

    "context"

    "github.com/micro/cli/v2"
    proto "github.com/micro/examples/service/proto"
    "github.com/micro/go-micro/v2"
    "github.com/micro/go-micro/v2/transport/grpc"
    "github.com/micro/go-plugins/registry/consul/v2"
)

/*

Example usage of top level service initialisation

*/

type Greeter struct{}

func (g *Greeter) Hello(ctx context.Context, req *proto.Request, rsp *proto.Response) error {
    rsp.Greeting = "Hello " + req.Name
    return nil
}

func main() {
    //reg := consul.NewRegistry()
    // Create a new service. Optionally include some options here.
    service := micro.NewService(
        micro.Name("greeter"),
        micro.Version("latest"),
        micro.Metadata(map[string]string{
            "type": "helloworld",
        }),
        micro.Registry(reg),
        micro.Transport(grpc.NewTransport()),

        // Setup some flags. Specify --run_client to run the client

        // Add runtime flags
        // We could do this below too
        micro.Flags(&cli.BoolFlag{
            Name:  "run_client",
            Usage: "Launch the client",
        }),
    )

    // Init will parse the command line flags. Any flags set will
    // override the above settings. Options defined here will
    // override anything set on the command line.
    service.Init(
        // Add runtime action
        // We could actually do this above
        micro.Action(func(c *cli.Context) error {
            if c.Bool("run_client") {
                runClient(service)
                os.Exit(0)
            }
            return nil
        }),
    )

    // By default we'll run the server unless the flags catch us

    // Setup the server

    // Register handler
    proto.RegisterGreeterHandler(service.Server(), new(Greeter))

    // Run the server
    if err := service.Run(); err != nil {
        fmt.Println(err)
    }
}

兩種方式使用插件,具體見[go-plugins使用說明](https://github.com/micro/go-p...segmentfault

  1. 第一種寫到plugins.go中,編譯的時候帶上plugins

go build -o service ./main.go ./plugins.goapp

啓動時經過命令行參數環境變量指定less

./service --registry=consulide

  1. 直接在import中聲明,並在micro.NewService()參數中指定,如上文例子

reg := consul.NewRegistry()函數

micro.Registry(reg),ui

那麼插件是何時生效的呢,this

micro.NewService()->newService(opts...)->newOptions(opts...)

// Registry sets the registry for the service
// and the underlying components
func Registry(r registry.Registry) Option {
    return func(o *Options) {
        o.Registry = r
        // Update router
        o.Router.Init(router.Registry(r))
        // Update server
        o.Server.Init(server.Registry(r))
        // Update Broker
        o.Broker.Init(broker.Registry(r))
    }
}

micro.Registry(reg)返回一個匿名函數設置了o.Registry爲傳進來的r
main()中聲明的reg := consul.NewRegistry(),在經過micro.Registry(reg),指定consul爲服務發現中心

func newOptions(opts ...Option) Options {
    opt := Options{
        Auth:      auth.DefaultAuth,
        Broker:    broker.DefaultBroker,
        Cmd:       cmd.DefaultCmd,
        Config:    config.DefaultConfig,
        Client:    client.DefaultClient,
        Server:    server.DefaultServer,
        Store:     store.DefaultStore,
        Registry:  registry.DefaultRegistry,
        Router:    router.DefaultRouter,
        Runtime:   runtime.DefaultRuntime,
        Transport: transport.DefaultTransport,
        Context:   context.Background(),
        Signal:    true,
    }
    fmt.Println("1", transport.DefaultTransport)

    for _, o := range opts {
        o(&opt)
    }
    fmt.Println("2", opt.Transport)

    return opt
}

在這裏依次調用了micro.NewService()參數中的設置函數設置各項參數,具體能夠看下「函數選項模式 Functional Options」,
這裏加了2行打印信息能夠直觀的查看狀況,輸出是

1 mdns      默認值
2 consul    opts設置生效後,變爲consul

go micro 分析系列文章
go micro server 啓動分析
go micro client
go micro broker
go micro cmd
go micro config
go micro store
go micro registry
go micro router
go micro runtime
go micro transport
go micro web
go micro registry 插件consul
go micro plugin
go micro jwt 網關鑑權
go micro 鏈路追蹤
go micro 熔斷與限流
go micro wrapper 中間件
go micro metrics 接入Prometheus、Grafana

相關文章
相關標籤/搜索