ToB企服应用市场:ToB评测及商务社交产业平台

标题: 微服务网关 —— SpringCloud Gateway [打印本页]

作者: 南七星之家    时间: 2023-9-3 20:27
标题: 微服务网关 —— SpringCloud Gateway
Gateway 简介

Spring Cloud Gateway 基于 Spring 5、Spring Boot 2 和 Project Reactor 等技术,是在 Spring 生态系统之上构建的 API 网关服务,Gateway 旨在提供一种简单而有效的方式来对 API 进行路由以及提供一些强大的过滤器功能,例如熔断、限流、重试等
Spring Cloud Gateway 具有如下特性:

Gateway 快速入门

创建项目,引入依赖
  1. <dependency>
  2.     <groupId>org.springframework.cloud</groupId>
  3.     <artifactId>spring-cloud-starter-gateway</artifactId>
  4. </dependency>
复制代码
在配置文件 application.yml 添加如下配置
  1. server:
  2.   port: 9201 # 指定运行端口
  3. spring:
  4.   application:
  5.     name: gateway-service # 指定服务名称
  6.   cloud:
  7.     gateway:
  8.       routes:
  9.         - id: path_route  # 路由ID
  10.           uri: http://localhost:8201/user/getUser  # 匹配后路由地址
  11.           predicates: # 断言,路径相匹配的路由
  12.             - Path=/user/getUser
复制代码
也可以按如下配置
  1. @Configuration
  2. public class GatewayConfig {
  3.     @Bean
  4.     public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
  5.         return builder.routes()
  6.                 .route("path_route2", r -> r.path("/user/getUserInfo")
  7.                         .uri("http://localhost:8201/user/getUserInfo"))
  8.                 .build();
  9.     }
  10. }
复制代码
Gateway 路由工厂

Spring Cloud Gateway 包括许多内置的路由断言工厂,所有这些断言都与 HTTP 请求的不同属性匹配,多个路由断言工厂可以进行组合
1. After Route Predicate Factory

在指定时间之后的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - After=2017-01-20T17:42:47.789-07:00[America/Denver]
复制代码
2. Before Route Predicate Factory

在指定时间之前的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
复制代码
3. Between Route Predicate Factory

在指定时间区间内的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
复制代码
4. Cookie Route Predicate Factory

带有指定 Cookie 的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Cookie=milk, yili # cookie为milk=yili
复制代码
5. Header Route Predicate Factory

带有指定请求头的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Header=X-Request-Id, 1        # 请求头为X-Request-Id=1
复制代码
6.  Host Route Predicate Factory

带有指定 Host 的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Host=**.somehost.org        # 请求头为Host:www.somehost.org的请求可以匹配该路由
复制代码
7.  Method Route Predicate Factory

发送指定方法的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Method=GET,POST
复制代码
8. Path Route Predicate Factory

发送指定路径的请求会匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Path=/red/(segment],/blue/(segment) # /red/1或/blue/1路径请求可以匹配该路由
复制代码
9. Query Route Predicate Factory

带指定查询参数的请求可以匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - Query=green # 带green=l查询参数的请求可以匹配该路由
复制代码
10. RemoteAddr Route Predicate Factory

从指定远程地址发起的请求可以匹配该路由
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: after_route
  6.           uri: http://example.org
  7.           predicates:
  8.             - RemoteAddr=192.168.1.1/24 # 从192.168.1.1发起请求可以匹配该路由
复制代码
11. Weight Route Predicate Factory

使用权重来路由相应请求,以下代码表示有 80% 的请求会被路由到 weighthigh.org,20% 会被路由到 weightlow.org
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: weight-high
  6.           uri: http://weighthigh.org
  7.           predicates:
  8.             - Weight=group1, 8
  9.         - id: weight-low
  10.           uri: http://weightlow.org
  11.           predicates:
  12.             - Weight=group1, 2
复制代码
可以使用 metadata 为每个 route 增加附加属性
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: route-with-metadata
  6.           uri: http://example.org
  7.           metadata:
  8.                   optionName: "OptionValue"
  9.                   compositeObject:
  10.                           name: "value"
  11.                   iAmNumber: 1
复制代码
可以从 exchange 获取所有元数据属性:
  1. Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
  2. route.getMetadata();
  3. route.getMetadata (someKey);
复制代码
Gateway 过滤器工厂

路由过滤器可用于修改进入的 HTTP 请求和返回的 HTTP 响应,Spring Cloud Gateway 内置了多种路由过滤器,由 GatewayFilter 的工厂类产生
1. AddRequestParameter GatewayFilter

AddRequestParameter GatewayFilter 是给请求添加参数的过滤器·
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: add_request_parameter_route
  6.           uri: http://example.org
  7.           filters:
  8.                   - AddRequestParameter=username, tom        # 对GET请求添加usemame=tom的请求参数
  9.           predicates:
  10.             - Method=GET
复制代码
2.  StripPrefixPath GatewayFilter

PrefixPath GatewayFilter 是对指定数量的路径前缓进行去除的过滤器
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: strip_prefix_route
  6.           uri: http://example.org
  7.           filters:
  8.                   # 把以/user-service/开头的请求的路径去除两位
  9.                   # 相当于http://1ocalhost:9201/user-service/a/user/1
  10.                   # 转换成http://localhost:8080/user/1
  11.                   - StripPrefix=2
  12.           predicates:
  13.             - Path=/user-service/**
复制代码
3.  PrefixPath GatewayFilter

与 StripPrefix 过滤器恰好相反,PrefixPath GatewayFilter 会对原有路径进行增加操作
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: prefix_prefix_route
  6.           uri: http://example.org
  7.           filters:
  8.                   # 对所有GET请求添加/user路径前缀
  9.                   # 相当于http://1ocalhost:9201/get
  10.                   # 转换成http://localhost:8080/user/get
  11.                   - PrefixPath=/user
  12.           predicates:
  13.             - Method-GET
复制代码
Gateway 全局过滤器

GlobalFilter 全局过滤器与普通的过滤器 GatewayFilter 具有相同的接口定义,只不过 GlobalFilter 会作用于所有路由
发起请求时,Filtering Web Handler 处理器会添加所有 GlobalFilter 实例和匹配的 GatewayFilter 实例到过滤器链中,过滤器链会使用 @Ordered 注解所指定的顺序进行排序,数值越小越靠前执行,默认 GatewayFilter 设置的 order 值为 1,如果 GatewayFilter 和 GlovalFilter 设置的 order 值一样,优先执行 GatewayFilter
  1. @Component
  2. public class CustomGlobalFilter implements GlobalFilter, ordered {
  3.    
  4.     @Override
  5.     public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  6.         log.info("custom global filter");
  7.         return chain.filter(exchange);
  8.     }
  9.    
  10.     @Override
  11.     public int getOrder() {
  12.         return -1;
  13.     }
  14. }
复制代码
Gateway 跨域

Gateway 是支持 CORS 的配置,可以通过不同的 URL 规则匹配不同的 CORS 策略,例如:
  1. spring:
  2.   cloud:
  3.     gateway:
  4.             globalcors:
  5.             corsConfiqurations:
  6.                 '[/**]':
  7.                     allowedOrigins: "https://docs.spring.io"
  8.                     allowedMethods:
  9.                         - GET
复制代码
在上面的示例中,对于所有 GET 请求,将允许来自 docs.spring.io 的 CORS 请求
Gateway 还提供更为详细的配置
  1. spring:
  2.   cloud:
  3.     gateway:
  4.             globalcors:
  5.             cors-confiqurations:
  6.                 '[/**]':
  7.                         # 允许携带认证信息
  8.                         allow-credentials: true
  9.                         # 允许跨城的源(网站城名/ip),设置*为全部
  10.                     allowed-origins:
  11.                     - "http://localhost:13009"
  12.                     - "http://localhost:13010"
  13.                     # 允许跨城请求里的head字段,设置*为全部
  14.                     allowed-headers: "*"
  15.                     # 允许跨城的method,默认为GET和OPTIONS,设置*为全部
  16.                     allowed-methods:
  17.                     - OPTIONS
  18.                     - GET
  19.                     - POST
  20.                     # 跨域允许的有效期
  21.                     max-age: 3600
  22.                     # 允许response的head信息
  23.                     # 默认仅允许如下6个:
  24.                     # Cache-Control
  25.                     # Content-Language
  26.                     # Content-Type
  27.                     # Expires
  28.                     # Last-Modified
  29.                     # Praqma
  30.                     # exposed-headers:
复制代码
HTTP 超时配置

1. 全局超时
  1. spring:
  2.   cloud:
  3.     gateway:
  4.             httpclient:
  5.                     connect-timeout: 1000 # 连接超时配置,单位为毫秒
  6.                     response-timeout: 5s # 响应超时,单位为 java.time.Duration
复制代码
2. 每个路由配置
  1. spring:
  2.   cloud:
  3.     gateway:
  4.       routes:
  5.         - id: per_route_timeouts
  6.           uri: http://example.org
  7.           predicates:
  8.             - Path=/user-service/**
  9.           metadata:
  10.                   response-timeout: 200 # 响应超时,单位为毫秒
  11.                   connect-timeout: 200 # 连接超时配置,单位为毫秒
复制代码
TLS/SSL 设置

在 Web 服务应用中,为了数据的传输安全,会使用安全证书以及 TLS/SSL 加密,Gateway 可以通过遵循常规的 Spring 服务器配置来侦听 HTTPS 上的请求
  1. server:
  2.         ssl:
  3.                 # 启用ssl
  4.                 enabled: true
  5.                 # 启用证书
  6.                 key-alias: scg
  7.                 # 证书密码
  8.                 key-store-password: scg1234
  9.                 # 证书地址
  10.                 key-store: classpath:scg-keystore.pl2
  11.                 # 证书类型
  12.                 key-store-type: PKCS12
复制代码
可以使用以下配置为 Gateway 配置一组可信任的已知证书
  1. spring:
  2.   cloud:
  3.     gateway:
  4.             httpclient:
  5.                     ssl:
  6.                             trustedX509Certificates:
  7.                 - certl.pem
  8.                 - cert2.pem
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4