api-breaker

定义

该插件实现 API 熔断功能,帮助我们保护上游业务服务。

关于熔断超时逻辑

由代码逻辑自动按触发不健康状态的次数递增运算:

每当上游服务返回unhealthy.http_statuses配置中的状态码(比如:500),达到unhealthy.failures次时(比如:3 次),认为上游服务处于不健康状态。

第一次触发不健康状态,熔断 2 秒

然后,2 秒过后重新开始转发请求到上游服务,如果继续返回unhealthy.http_statuses状态码,记数再次达到unhealthy.failures次时,熔断 4 秒(倍数方式)。

依次类推,2, 4, 8, 16, 32, 64, …, 256, 最大到 300。 300 是 max_breaker_sec 的最大值,允许自定义修改。

在不健康状态时,当转发请求到上游服务并返回healthy.http_statuses配置中的状态码(比如:200),达到healthy.successes次时(比如:3 次),认为上游服务恢复健康状态。

属性列表

名称 类型 必选项 默认值 有效值 描述
break_response_code integer 必须 [200, …, 599] 不健康返回错误码
max_breaker_sec integer 可选 300 >=60 最大熔断持续时间
unhealthy.http_statuses array[integer] 可选 {500} [500, …, 599] 不健康时候的状态码
unhealthy.failures integer 可选 3 >=1 触发不健康状态的连续错误请求次数
healthy.http_statuses array[integer] 可选 {200} [200, …, 499] 健康时候的状态码
healthy.successes integer 可选 3 >=1 触发健康状态的连续正常请求次数

启用方式

这是一个示例,在指定的路由上启用api-breaker插件。 应答 500 或 503 连续 3 次,触发熔断。应答 200 连续 1 次,恢复健康。

  1. curl "http://127.0.0.1:9080/apisix/admin/routes/1" -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "plugins": {
  4. "api-breaker": {
  5. "break_response_code": 502,
  6. "unhealthy": {
  7. "http_statuses": [500, 503],
  8. "failures": 3
  9. },
  10. "healthy": {
  11. "http_statuses": [200],
  12. "successes": 1
  13. }
  14. }
  15. },
  16. "uri": "/hello",
  17. "host": "127.0.0.1"
  18. }'

测试插件

使用上游的配置,如果你的上流服务返回 500,连续 3 次。客户端将会收到 502(break_response_code)应答。

  1. $ curl -i "http://127.0.0.1:9080/get"
  2. HTTP/1.1 502 Bad Gateway
  3. Content-Type: application/octet-stream
  4. Connection: keep-alive
  5. Server: APISIX/1.5
  6. ... ...

禁用插件

当想禁用api-breaker插件时,非常简单,只需要在插件配置中删除相应的 json 配置,无需重启服务,即可立即生效:

  1. curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "uri": "/hello",
  4. "upstream": {
  5. "type": "roundrobin",
  6. "nodes": {
  7. "127.0.0.1:1980": 1
  8. }
  9. }
  10. }'

api-breaker 插件现在已被禁用,它也适用于其他插件。