Hystrix是 Netflix 的一个非常棒的项目。

Hystrix 是一个延迟和容错库,旨在隔离对远程系统、服务和第三方库的访问点,防止级联故障,并在故障不可避免的复杂分布式系统中实现弹性。

我认为程序员定义的回退(fallbacks)和自适应健康监控的 Hystrix 模式适用于任何分布式系统。Goroutines和channels是很好的并发原语,但不能直接帮助我们的应用程序在故障期间保持可用。

hystrix-go旨在让 Go 程序员轻松构建具有与基于 Java 的 Hystrix 库类似的执行语义的应用程序。

如何使用

import "github.com/afex/hystrix-go/hystrix"

将代码作为 Hystrix 命令执行

hystrix.Go
hystrix.Go("my_command", func() error {
 // talk to other services
 return nil
}, nil)

定义回退行为

hystrix.Go

当代码返回一个错误时,或者当它基于各种健康检查无法完成时,就会触发此事件。

hystrix.Go("my_command", func() error {
 // talk to other services
 return nil
}, func(err error) error {
 // do this when services are down
 return nil
})

等待输出

hystrix.Go
output := make(chan bool, 1)
errors := hystrix.Go("my_command", func() error {
 // talk to other services
 output <- true
 return nil
}, nil)

select {
case out := <-output:
 // success
case err := <-errors:
 // failure
}

同步 API

hystrix.Do
err := hystrix.Do("my_command", func() error {
 // talk to other services
 return nil
}, nil)

配置设置

hystrix.ConfigureCommand()
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
 Timeout:               1000,
 MaxConcurrentRequests: 100,
 ErrorPercentThreshold: 25,
})
hystrix.Configure()map[string]CommandConfig

如何启用仪表板指标

在你的 main.go 中,在端口上注册事件流 HTTP 处理程序并在 goroutine 中启动它。一旦你为Hystrix 仪表板[6]配置了涡轮机以开始流式传输事件,你的命令将自动开始出现。

在 main.go 中,在端口上注册事件流 HTTP 处理程序,并在 goroutine 中启动它。一旦为 Hystrix 仪表板配置了涡轮机(turbine)以启动流事件,命令将自动开始显示。

hystrixStreamHandler := hystrix.NewStreamHandler()
hystrixStreamHandler.Start()
go http.ListenAndServe(net.JoinHostPort("", "81"), hystrixStreamHandler)

将circuit指标发送到 Statsd

c, err := plugins.InitializeStatsdCollector(&plugins.StatsdCollectorConfig{
 StatsdAddr: "localhost:8125",
 Prefix:     "myapp.hystrix",
})
if err != nil {
 log.Fatalf("could not initialize statsd client: %v", err)
}

metricCollector.Registry.Register(c.NewStatsdCollector)

FAQ

如果我的运行函数发生了panic会怎么样?hystrix-go 会触发回退吗?

recover()

如何构建和测试

vagrant upvagrant sshcd /go/src/github.com/afex/hystrix-gogo test ./...