前言
本文主要研究一下spring cloud gateway如何集成hystrix。
当下游接口负载很大,或者接口不通等其他原因导致超时,如果接口不熔断的话将会影响到下游接口得不到喘息,网关也会因为超时连接一直挂起,很可能因为一个子系统的问题导致整个系统的雪崩。所以我们的网关需要设计熔断,当因为熔断器打开时,网关将返回一个降级的应答。
 Maven配置
添加hystrix依赖
pom.xml
1 2 3 4
   | <dependency>     <groupId>org.springframework.cloud</groupId>     <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
   | 
 
 项目实战
- 在 
provider1 服务中添加一个方法,延时2秒返回响应。 
1 2 3 4 5 6 7 8 9 10
   | @GetMapping("/timeout") public String timeout() {     try {         Thread.sleep(2000);     } catch (InterruptedException e) {         e.printStackTrace();     }     System.out.println("休眠了2秒");     return "timeout test"; }
  | 
 
- 修改网关配置文件
 
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
   | server:   port: 2000 spring:   application:     name: idc-gateway2   redis:     host: localhost     port: 6379     timeout: 6000ms       jedis:       pool:         max-active: 1000           max-wait: -1ms               max-idle: 10               min-idle: 5          cloud:     consul:       host: localhost       port: 8500     gateway:       discovery:         locator:           enabled: true        routes:         - id: provider1           uri: lb://idc-provider1           predicates:             - Path=/p1/**           filters:             - StripPrefix=1             - name: Hystrix               args:                 name: default                 fallbackUri: forward:/defaultfallback          - id: provider2           uri: lb://idc-provider2           predicates:             - Path=/p2/**           filters:             - StripPrefix=1
 
  hystrix:   command:     default:       execution:         isolation:           strategy: SEMAPHORE           thread:             timeoutInMilliseconds: 1500
   | 
 
- 网关添加降级处理类
 
1 2 3 4 5 6 7 8 9 10 11 12 13
   | @RestController public class FallbackController {
      @RequestMapping("/defaultfallback")     public Map<String,Object> defaultfallback(){         System.out.println("降级操作...");         Map<String,Object> map = new HashMap<>();         map.put("code",200);         map.put("msg","服务超时降级");         map.put("data",null);         return map;     } }
   | 
 
 降级测试
- 超时服务降级
 
1
   | curl http://localhost:2000/p1/timeout
   | 
 
返回
1
   | {"msg":"服务超时降级","code":200,"data":null}
  | 
 
- 其他异常
 
spring-cloud-gateway 调用下游服务返回的异常,网关不做任何处理,会直接返回。大家想一下为什么在网关不去处理下游异常呢? 因为很多时候下游的异常是包含有效信息的(异常信息千千万),如果在网关处做了统一返回,就失去了返回异常的意义。
spring-cloud-starter-netflix-hystrix 内置的Hystrix过滤器是
HystrixGatewayFilterFactory。 感兴趣的小伙伴可以自行阅读相关源码。
 结语
本文到此结束,感谢大家的阅读。欢迎大家关注公众号【当我遇上你】。