Spring Cloud Gateway 微服务网关
-
创建项目(命名 为 Gateway), 添加pom 依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> <version>2.2.0.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2.2.0.RELEASE</version> </dependency>
-
Router 路由器:包括,11种路由模式,具体参见官网
-
添加路由配置: 意思是所有路径匹配到 /acc/** ,都会路由到 lb://account-service
spring: cloud: gateway: routes: - id: host_route uri: lb://account-service predicates: - Path=/acc/**
-
在启动类添加注解,服务注册和发现
@EnableDiscoveryClient public class GatewayApplication { }
-
测试
- 默认路由地址:http://localhost:9001/account-service/acc/user?id=2
- 使用Path路由配置:http://localhost:9001/acc/user?id=2
-
打开gateway 监控端点 ,各端点介绍,参见Gateway管理API
<!-- 添加 actuator 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
#将 gateway 端点暴露 management.endpoint.gateway.enabled=true management.endpoints.web.exposure.include=gateway
查询全局过滤器, http://localhost:9001/actuator/gateway/globalfilters 查询路由中的过滤器, http://localhost:9001/actuator/gateway/routefilters 刷新路由缓存, http://localhost:9001/actuator/gateway/refresh 展示路由列表, http://localhost:9001/actuator/gateway/routes 获取单个路由的信息, http://localhost:9001/actuator/gateway/routes/host_route 创建路由,发送Post请求, ../actuator/gateway/routes/{id_route_to_create} 删除路由,发送Delete请求: ../actuator/gateway/routes/{id_route_to_delete}
-
-
Filter 过滤器
-
网关经常需要对路由请求进行过滤,如鉴权之后构造头部之类的,过滤的种类很多,如增加请求头、增加请求参数 、增加响应头和断路器等等功能,这就用到了Spring Cloud Gateway 的 Filter。
-
Filter 的作用:
- 当我们有很多个服务时,客户端请求各个服务的Api时,每个服务都需要做相同的事情,比如鉴权、限流、日志输出等。
- 因此可以将这些功能等转移到网关处理以减少重复开发。
-
- PRE: 这种过滤器在被代理的微服务(Proxied Service)执行之前调用。我们可利用这种过滤器实现身份验证、在集群中选择请求的微服务、记录调试信息等。
- POST:这种过滤器在被代理的微服务(Proxied Service)执行完成后执行。这种过滤器可用来为响应添加标准的 HTTP Header、收集统计信息和指标、将响应从微服务发送给客户端等。
-
Filter 的分类
-
GatewayFilter:应用到单个路由或者一个分组的路由上。自定义的GatewayFilter,同样需要指定某个路由器
-
GlobalFilter:应用到所有的路由上。当请求到来时,
Filtering Web Handler
处理器会添加所有GlobalFilter
实例和匹配的GatewayFilter
实例到过滤器链中。因此,自定义的GlobalFilter,不需要什么额外的配置。 -
自定义 GatewayFilter,有两种实现方式
-
一种是直接 实现GatewayFilter接口,不过还需要手动将自定义的GatewayFilter 注册到 router中
// 统计某个或者某种路由的处理时长 public class CustomerGatewayFilter implements GatewayFilter, Ordered { private static final Logger log = LoggerFactory.getLogger( CustomerGatewayFilter.class ); private static final String COUNT_START_TIME = "countStartTime"
-
-