【问题标题】:why nsqlookupd package use Context?为什么 nsqlookupd 包使用上下文?
【发布时间】:2017-10-24 05:55:32
【问题描述】:

在阅读nsq源码的nsqlookupd部分时,发现作者使用了一个Context truct来包装一个NSQLookupd struct而没有其他的funcs用于Context。不知道为什么要这样使用,对我们有什么好处可以通过这种方式得到吗?下面的源代码在这里。谢谢!

context.go

type Context struct {
    nsqlookupd *NSQLookupd
}

nsqlookupd.go

func (l *NSQLookupd) Main() {
ctx := &Context{l}

tcpListener, err := net.Listen("tcp", l.opts.TCPAddress)
if err != nil {
    l.logf(LOG_FATAL, "listen (%s) failed - %s", l.opts.TCPAddress, err)
    os.Exit(1)
}
l.Lock()
l.tcpListener = tcpListener
l.Unlock()
tcpServer := &tcpServer{ctx: ctx}
l.waitGroup.Wrap(func() {
    protocol.TCPServer(tcpListener, tcpServer, l.opts.Logger)
})

【问题讨论】:

    标签: go nsq


    【解决方案1】:

    因为面向未来。

    Context struct 提供了一种将特定于上下文的数据包装到单个结构中的方法。此时上下文只包含一个指向NSQLookupd 结构的指针。但是,如果Context 需要以某种方式扩展,那么您所要做的就是向结构添加更多字段。你也可以实现结构体方法。

    所有这些都不需要更改程序中的内部 API,因为所有这些新字段和方法都包装在结构中,并且已经在程序中传递。您很可能必须更改 struct 的初始化方式。

    【讨论】:

    • 酷!非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多