栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Options的理解和在go-micro中的使用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Options的理解和在go-micro中的使用

person2 : NewPerson(WithPersonProperty( dongxiaojian , 18, 1, 180) ,WithRegional( china , hebei ))

go-micrio中的例子 它的主要用到的类型/组件都封装在了Options中

type Options struct {
 Auth auth.Auth
 Broker broker.Broker
 Cmd cmd.Cmd
 Config config.Config
 Client client.Client
 Server server.Server
 Store store.Store
 Registry registry.Registry
 Runtime runtime.Runtime
 Transport transport.Transport
 Profile profile.Profile
 // Before and After funcs
 BeforeStart []func() error
 BeforeStop []func() error
 AfterStart []func() error
 AfterStop []func() error
 // Other options for implementations of the interface
 // can be stored in a context
 Context context.Context
 Signal bool

Service是interface的类型 Options 接口返回Options结构体 迷惑命名

type Service interface {
 // The service name
 Name() string
 // Init initialises options
 Init(...Option)
 // Options returns the current options
 Options() Options
 // Client is used to call services
 Client() client.Client
 // Server is for handling requests and events
 Server() server.Server
 // Run the service
 Run() error
 // The service implementation
 String() string

对一个微服务Service初始化 要初始化其中的Options结构体

// NewService creates and returns a new Service based on the packages within.
func NewService(opts ...Option) Service {
 return newService(opts...)
func newService(opts ...Option) Service {
// .....
 options : newOptions(opts...)
//省略其他代码
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,
 Runtime: runtime.DefaultRuntime,
 Transport: transport.DefaultTransport,
 Context: context.Background(),
 Signal: true,
//遍历Option函数来对Options结构体的opt对象初始化 迷惑的命名 
 for _, o : range opts {
 o( opt)
 return opt

比如我想用一个特定的Registry注册中心来初始化Options结构体 Registry函数是初始化操作Options结构体的函数之一 返回的是Option也就是函数

// 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 Client and Server
 o.Client.Init(client.Registry(r))
 o.Server.Init(server.Registry(r))
 // Update Broker
 o.Broker.Init(broker.Registry(r))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/267939.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号