添加上依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
配置示例
spring:
cloud:
gateway:
routes:
- id: hystrix_route
uri: http://example.org
filters:
- Hystrix=myCommandName
配置后,gateway 将使用 myCommandName 作为名称生成 HystrixCommand 对象来进行熔断管理。如果想添加熔断后的回调内容,需要在添加一些配置。
spring:
cloud:
gateway:
routes:
- id: ingredients
uri: lb://ingredients
predicates:
- Path=//ingredients/**
filters:
- name: Hystrix
args:
name: fallbackcmd
fallbackUri: forward:/fallback
fallbackUri: forward:/fallback配置了 fallback 时要会调的路径,当调用 Hystrix 的 fallback 被调用时,请求将转发到/fallback这个 URI。
定义fallback 路径controller
@RestController
@RequestMapping("/fallback")
public class FallbackController {
@RequestMapping("")
public String fallback(){
return "error";
}
}
- 也可以在配置文件中定义fallback 转发到其他路径
spring:
cloud:
gateway:
routes:
- id: ingredients
uri: lb://ingredients
predicates:
- Path=//ingredients/**
filters:
- name: Hystrix
args:
name: fallbackcmd
fallbackUri: forward:/fallback
- id: ingredients-fallback
uri: http://localhost:9994
predicates:
- Path=/fallback
在本例中,gateway应用程序中没有 fallback 实现,但是另一个应用程序中有一个接口实现,访问路径为http://localhost:9994
hystrix配置参数(如 timeouts)可以使用全局默认值配置,也可以使用Hystrix 所述属性进行配置。
要为上面的示例路由设置5秒超时,将使用以下配置
hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000