2 回答
TA贡献1847条经验 获得超7个赞
你把它倒过来了。您的解决方案应该遵循问题的形状,而不是特定解决方案的形状。解决方案中没有任何内容值得重构。它只会增加毫无意义的复杂性。
例如,
package main
import "github.com/nsqio/go-nsq"
// NewProducer is nsq.NewProducer with retries of an address list.
func NewProducer(addrs []string, config *nsq.Config) (producer *nsq.Producer, err error) {
if len(addrs) == 0 {
addrs = append(addrs, "")
}
for _, addr := range addrs {
producer, err = nsq.NewProducer(addr, config)
if err == nil {
break
}
}
return producer, err
}
// ConnectToNSQD is nsq.ConnectToNSQD with retries of an address list.
func ConnectToNSQD(c *nsq.Consumer, addrs []string) (err error) {
if len(addrs) == 0 {
addrs = append(addrs, "")
}
for _, addr := range addrs {
err = c.ConnectToNSQD(addr)
if err == nil {
break
}
}
return err
}
func main() {}
TA贡献1817条经验 获得超14个赞
也许像这样?
var publisher *nsq.Producer
connectToWorkingIP(ips, func(ip string) error {
var err error
publisher, err = nsq.NewProducer(ip, nsq.NewConfig())
return err
})
connectToWorkingIP(ips, func(ip string) error {
return consumer.ConnectToNSQD(ip)
})
func connectToWorkingIP(ips []string, f func(string) error) {
for i, success := 0, false; i < len(ips) && !success; i++ {
err := f(ips[i])
if err == nil {
success = true
}
}
}
- 2 回答
- 0 关注
- 144 浏览
添加回答
举报