熔断器 Hystrix-go
hystrix-go是用go实现的hystrix版,提供了基础的熔断、降级功能。
项目中应用
完整代码:
https://github.com/Justin02180218/micro-kit
在 pkg 下新建目录 circuitbreakers,创建 hystrix.go 文件:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27import "github.com/afex/hystrix-go/hystrix" func Hystrix(commandName, fallbackMsg string) endpoint.Middleware { return func(next endpoint.Endpoint) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { err = hystrix.Do( commandName, // 熔断开关 func() error { response, err = next(ctx, request) return err }, // 降级 func(err error) error { fmt.Println("fallbackErrorDesc", err.Error()) response = struct { Fallback string `json:"fallback"` }{fallbackMsg} return nil }) if err != nil { return nil, err } return } } }
在 go kit 的 endpoint 层进行限流,采用装饰器模式。
我们在 user-service 微服务中调用 book-rpc-service 微服务的接口加入熔断器:
配置文件
配置 hystrix 流数据接口,用于 hystrix-dashboard 收集数据。
1
2hystrix: stream_port: 9000
1
2
3type HystrixConfig struct { StreamPort string `json:"streamport" yaml:"streamport"` }
修改 main.go
1
2
3
4
5
6
7
8
9
10import "github.com/afex/hystrix-go/hystrix" hystrix.ConfigureCommand("Find books", hystrix.CommandConfig{Timeout: 1000}) grpcClient = circuitbreakers.Hystrix("Find books", "book-rpc-service currently unavailable")(grpcClient) hystrixStreamStreamHandler := hystrix.NewStreamHandler() hystrixStreamStreamHandler.Start() go func() { errChan <- http.ListenAndServe(net.JoinHostPort("", configs.Conf.HystrixConfig.StreamPort), hystrixStreamStreamHandler) }()
启动 hystrix-dashboard
使用 Docker 启动 hystrix-dashboard:
docker pull mlabouardy/hystrix-dashboard
docker run -p 8181:9002 --name hystrix-dashboard mlabouardy/hystrix-dashboard:latest
在浏览器地址栏输入:http://localhost:8181/hystrix 查看接口请求信息
测试
启动 user-service 微服务,但是不启动 book-rpc-service 微服务,接口快速返回熔断降级信息:
启动 book-rpc-service 微服务,接口返回书籍列表:
下一篇文章,我们基于Consul写一个简单的网关服务(library-apigateway)。
完整代码:
https://github.com/Justin02180218/micro-kit
更多【分布式专辑】【架构实战专辑】系列文章,请关注公众号
最后
以上就是失眠龙猫最近收集整理的关于八,熔断、降级的全部内容,更多相关八内容请搜索靠谱客的其他文章。
发表评论 取消回复