我是靠谱客的博主 失眠龙猫,这篇文章主要介绍八,熔断、降级,现在分享给大家,希望可以做个参考。

熔断器 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
27
import "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
2
hystrix: stream_port: 9000
复制代码
1
2
3
type HystrixConfig struct { StreamPort string `json:"streamport" yaml:"streamport"` }

 

修改 main.go

复制代码
1
2
3
4
5
6
7
8
9
10
import "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


更多【分布式专辑】【架构实战专辑】系列文章,请关注公众号

 

 

 

最后

以上就是失眠龙猫最近收集整理的关于八,熔断、降级的全部内容,更多相关内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部