6Gateway FallBack · SpringCloud微服务实战 · 看云
6. Gateway FallBack
导航
前面我们在入门篇讲到
Zuul的FallBack,并且我们在讲Hystrix也说到在一个分布式系统架构中FallBack的作用。服务B出现的问题不应该影响服务A,在服务B可用的时候继续提供服务。这样保证了服务之间是隔离的,不会产生雪崩式的不可用。
Spring Cloud Gateway 提供了Hystrix GatewayFilter Factory,Hystrix GatewayFilter允许你向网关路由引入断路器,保护你的服务不受级联故障的影响,并允许你在下游故障时提供fallback响应。
本节代码地址
GitHub: https://github.com/xuyisu/fw-sping-cloud/tree/master/fw-cloud-gateways/fw-cloud-gateways-gateway
6.1 添加hystrix 依赖
要在项目中启用Hystrix网关过滤器,需要添加对 spring-cloud-starter-netflix-hystrix的依赖 Spring Cloud Netflix.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
6.2 应用配置
Hystrix GatewayFilter Factory 需要一个name参数,即HystrixCommand的名称,设置过滤器名称为Hystrix,并且设置fallback的地址为重定向到我们自己定义的接口。fw-cloud-ribbon-server会作为参数。
server:
port: 8711
spring:
application:
name: fw-gateways-gateway
profiles:
active: hystrix_route
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
---
spring:
cloud:
gateway:
routes:
- id: hystrix_route
uri: lb://fw-cloud-ribbon-server
predicates:
- After=2020-01-08T18:30:11.965+08:00[Asia/Shanghai]
filters:
- name: Hystrix
args:
name: fallback
fallbackUri: forward:/fallback/fw-cloud-ribbon-server
profiles: hystrix_route
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
6.3 FallBack 接收
控制层接收服务名。这样如果一个服务不可用,会将服务不可用的信息返回。这里只是掩饰,读者可以用自己的业务去丰富这个功能。
@RestController
public class FallbackController {
@RequestMapping("fallback/{name}")
public Mono<FwResult> systemFallback(@PathVariable String name) {
String response = String.format("访问%s超时或者服务不可用", name);
return Mono.just(FwResult.failedMsg(response));
}
}
6.4 应用启动
我们将ribbon-server 关掉
通过访问localhost:8711/user/1可以看到


