Spring Cloud Gateway是Spring Cloud家族的第二代网关。其主要功能是通过过滤器来实现的。根据过滤器的作用范围划分为GatewayFilter和GlobalFilter,二者区别如下:
GatewayFilter : 需要通过spring.cloud.routes.filters 配置在具体路由下,只作用在当前路由上或通过spring.cloud.default-filters配置在全局,作用在所有路由上。
GlobalFilter : 全局过滤器,不需要在配置文件中配置,作用在所有的路由上,最终通过GatewayFilterAdapter包装成GatewayFilterChain可识别的过滤器,它为请求业务以及路由的URI转换为真实业务服务的请求地址的核心过滤器,不需要配置,系统初始化时加载,并作用在每个路由上。
spring cloud gateway如何集成hystrix,就是通过filter实现的。
首先在gateway项目中引入hystrix的maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
然后在配置文件中spring.cloud.gateway下增加如下配置
default-filters:
- name: Hystrix
args:
name: fallbackcmd
fallbackUri: forward:/fallbackcontroller
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 30000
- 首先filter里头配置了name为Hystrix的filter,实际是对应HystrixGatewayFilterFactory
- 然后指定了hystrix command的名称,及fallbackUri,注意fallbackUri要以forward开头
- 最后通过hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds指定该command的超时时间
写于2020年端午节