spring cloud gateway集成hystrix全局断路器

2022-07-05 14:38:51

pom.xml添加依赖

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>

</dependency>

在配置文件中,增加spring.cloud.gateway.default-filters

default-filters:
- name: Hystrix
  args:
    name: fallbackcmd
    fallbackUri: forward:/fallbackcontroller

一定要注意是spring.cloud.gateway.default-filters这个配置节。

如上的配置,将会使用HystrixCommand打包剩余的过滤器,并命名为fallbackcmd,我们还配置了可选的参数fallbackUri,降级逻辑被调用,请求将会被转发到URI为/fallbackcontroller的控制器处理。定义降级处理如下:

@RequestMapping(value = "/fallbackcontroller")
public Map<String, String> fallBackController() {
    Map<String, String> res = new HashMap();
    res.put("code", "-100");
    res.put("data", "service not available");
    return res;
}

此时可以设置hystrix超时时间(毫秒) ,默认只有2秒

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 30000

示例代码:

https://github.com/wanghongqi/springcloudconsul_test/tree/master/springtest_gateway

  • 作者:草宝虫
  • 原文链接:https://wanghq.blog.csdn.net/article/details/88179419
    更新时间:2022-07-05 14:38:51