Gateway 简介

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

Spring Cloud Gateway 具有如下特性:

  • 基于 Spring Framework 5、Project Reactor 以及 Spring Boot 2.0 进行构建
  • 能够匹配任何请求属性
  • 可以对路由指定 Predicate(断言)和 Filter(过滤器)
  • 集成 Hystrix 的断路器功能
  • 集成 Spring Cloud 服务发现功能
  • 易于编写的 Predicate 和 Filter
  • 请求限流功能
  • 路径重写

Gateway 快速入门

创建项目,引入依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

在配置文件 application.yml 添加如下配置

server:
port: 9201 # 指定运行端口 spring:
application:
name: gateway-service # 指定服务名称
cloud:
gateway:
routes:
- id: path_route # 路由ID
uri: http://localhost:8201/user/getUser # 匹配后路由地址
predicates: # 断言,路径相匹配的路由
- Path=/user/getUser

也可以按如下配置

@Configuration
public class GatewayConfig { @Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route2", r -> r.path("/user/getUserInfo")
.uri("http://localhost:8201/user/getUserInfo"))
.build();
}
}

如果整合 Nacos 注册中心并配置多实例作负载均衡则在配置文件 application.yml 如下配置

spring:
cloud:
gateway:
routes:
- id: service-01
uri: lb://service-01 # service-01是在nacos注册的服务名,lb://表示启用负载均衡
predicates:
- Path=/service-01/**
- id: service-02
uri: lb://service-02
predicates:
- Path=/service-02/**

Gateway 路由工厂

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

1. After Route Predicate Factory

在指定时间之后的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: after_route
uri: http://example.org
predicates:
- After=2017-01-20T17:42:47.789-07:00[America/Denver]

2. Before Route Predicate Factory

在指定时间之前的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: before_route
uri: http://example.org
predicates:
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]

3. Between Route Predicate Factory

在指定时间区间内的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: between_route
uri: http://example.org
predicates:
- 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 的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: http://example.org
predicates:
- Cookie=milk, yili # cookie为milk=yili

5. Header Route Predicate Factory

带有指定请求头的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: header_route
uri: http://example.org
predicates:
- Header=X-Request-Id, 1 # 请求头为X-Request-Id=1

6. Host Route Predicate Factory

带有指定 Host 的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: host_route
uri: http://example.org
predicates:
- Host=**.somehost.org # 请求头为Host:www.somehost.org的请求可以匹配该路由

7. Method Route Predicate Factory

发送指定方法的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: method_route
uri: http://example.org
predicates:
- Method=GET,POST

8. Path Route Predicate Factory

发送指定路径的请求会匹配该路由

spring:
cloud:
gateway:
routes:
- id: path_route
uri: http://example.org
predicates:
- Path=/red/{segment},/blue/{segment} # /red/1或/blue/1路径请求可以匹配该路由

9. Query Route Predicate Factory

带指定查询参数的请求可以匹配该路由

spring:
cloud:
gateway:
routes:
- id: query_route
uri: http://example.org
predicates:
- Query=green # 带green=l查询参数的请求可以匹配该路由

10. RemoteAddr Route Predicate Factory

从指定远程地址发起的请求可以匹配该路由

spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: http://example.org
predicates:
- RemoteAddr=192.168.1.1/24 # 从192.168.1.1发起请求可以匹配该路由

11. Weight Route Predicate Factory

使用权重来路由相应请求,以下代码表示有 80% 的请求会被路由到 weighthigh.org,20% 会被路由到 weightlow.org

spring:
cloud:
gateway:
routes:
- id: weight_high
uri: http://weighthigh.org
predicates:
- Weight=group1, 8
- id: weight-low
uri: http://weightlow.org
predicates:
- Weight=group1, 2

可以使用 metadata 为每个 route 增加附加属性

spring:
cloud:
gateway:
routes:
- id: route-with-metadata
uri: http://example.org
metadata:
optionName: "OptionValue"
compositeObject:
name: "value"
iAmNumber: 1

可以从 exchange 获取所有元数据属性:

Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
route.getMetadata();
route.getMetadata (someKey);

Gateway 过滤器工厂

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

1. AddRequestParameter GatewayFilter

AddRequestParameter GatewayFilter 是给请求添加参数的过滤器·

spring:
cloud:
gateway:
routes:
- id: add_request_parameter_route
uri: http://example.org
filters:
- AddRequestParameter=username, tom # 对GET请求添加usemame=tom的请求参数
predicates:
- Method=GET

2. StripPrefixPath GatewayFilter

PrefixPath GatewayFilter 是对指定数量的路径前缓进行去除的过滤器

spring:
cloud:
gateway:
routes:
- id: strip_prefix_route
uri: http://example.org
filters:
# 把以/user-service/开头的请求的路径去除两位
# 相当于http://1ocalhost:9201/user-service/a/user/1
# 转换成http://localhost:8080/user/1
- StripPrefix=2
predicates:
- Path=/user-service/**

3. PrefixPath GatewayFilter

与 StripPrefix 过滤器恰好相反,PrefixPath GatewayFilter 会对原有路径进行增加操作

spring:
cloud:
gateway:
routes:
- id: prefix_prefix_route
uri: http://example.org
filters:
# 对所有GET请求添加/user路径前缀
# 相当于http://1ocalhost:9201/get
# 转换成http://localhost:8080/user/get
- PrefixPath=/user
predicates:
- Method-GET

Gateway 全局过滤器

GlobalFilter 全局过滤器与普通的过滤器 GatewayFilter 具有相同的接口定义,只不过 GlobalFilter 会作用于所有路由

发起请求时,Filtering Web Handler 处理器会添加所有 GlobalFilter 实例和匹配的 GatewayFilter 实例到过滤器链中,过滤器链会使用 @Ordered 注解所指定的顺序进行排序,数值越小越靠前执行,默认 GatewayFilter 设置的 order 值为 1,如果 GatewayFilter 和 GlovalFilter 设置的 order 值一样,优先执行 GatewayFilter

@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered { @Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("custom global filter");
return chain.filter(exchange);
} @Override
public int getOrder() {
return -1;
}
}

Gateway 跨域

Gateway 是支持 CORS 的配置,可以通过不同的 URL 规则匹配不同的 CORS 策略,例如:

spring:
cloud:
gateway:
globalcors:
corsConfiqurations:
'[/**]':
allowedOrigins: "https://docs.spring.io"
allowedMethods:
- GET

在上面的示例中,对于所有 GET 请求,将允许来自 docs.spring.io 的 CORS 请求

Gateway 还提供更为详细的配置

spring:
cloud:
gateway:
globalcors:
cors-confiqurations:
'[/**]':
# 允许携带认证信息
allow-credentials: true
# 允许跨城的源(网站城名/ip),设置*为全部
allowed-origins:
- "http://localhost:13009"
- "http://localhost:13010"
# 允许跨城请求里的head字段,设置*为全部
allowed-headers: "*"
# 允许跨城的method,默认为GET和OPTIONS,设置*为全部
allowed-methods:
- OPTIONS
- GET
- POST
# 跨域允许的有效期
max-age: 3600
# 允许response的head信息
# 默认仅允许如下6个:
# Cache-Control
# Content-Language
# Content-Type
# Expires
# Last-Modified
# Praqma
# exposed-headers:

HTTP 超时配置

1. 全局超时

spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000 # 连接超时配置,单位为毫秒
response-timeout: 5s # 响应超时,单位为 java.time.Duration

2. 每个路由配置

spring:
cloud:
gateway:
routes:
- id: per_route_timeouts
uri: http://example.org
predicates:
- Path=/user-service/**
metadata:
response-timeout: 200 # 响应超时,单位为毫秒
connect-timeout: 200 # 连接超时配置,单位为毫秒

TLS/SSL 设置

在 Web 服务应用中,为了数据的传输安全,会使用安全证书以及 TLS/SSL 加密,Gateway 可以通过遵循常规的 Spring 服务器配置来侦听 HTTPS 上的请求

server:
ssl:
# 启用ssl
enabled: true
# 启用证书
key-alias: scg
# 证书密码
key-store-password: scg1234
# 证书地址
key-store: classpath:scg-keystore.pl2
# 证书类型
key-store-type: PKCS12

可以使用以下配置为 Gateway 配置一组可信任的已知证书

spring:
cloud:
gateway:
httpclient:
ssl:
trustedX509Certificates:
- certl.pem
- cert2.pem

微服务网关 —— SpringCloud Gateway的更多相关文章

  1. SpringCloud Gateway微服务网关实战与源码分析-上

    概述 定义 Spring Cloud Gateway 官网地址 https://spring.io/projects/spring-cloud-gateway/ 最新版本3.1.3 Spring Cl ...

  2. 微服务网关 Spring Cloud Gateway

    1.  为什么是Spring Cloud Gateway 一句话,Spring Cloud已经放弃Netflix Zuul了.现在Spring Cloud中引用的还是Zuul 1.x版本,而这个版本是 ...

  3. 微服务网关实战——Spring Cloud Gateway

    导读 作为Netflix Zuul的替代者,Spring Cloud Gateway是一款非常实用的微服务网关,在Spring Cloud微服务架构体系中发挥非常大的作用.本文对Spring Clou ...

  4. 【SpringCloud构建微服务系列】微服务网关Zuul

    一.为什么要用微服务网关 在微服务架构中,一般不同的微服务有不同的网络地址,而外部客户端(如手机APP)可能需要调用多个接口才能完成一次业务需求.例如一个电影购票的手机APP,可能会调用多个微服务的接 ...

  5. springcloud(十四):搭建Zuul微服务网关

    springcloud(十四):搭建Zuul微服务网关 1. 2. 3. 4.

  6. 小D课堂 - 新版本微服务springcloud+Docker教程_6-06 zuul微服务网关集群搭建

    笔记 6.Zuul微服务网关集群搭建     简介:微服务网关Zull集群搭建 1.nginx+lvs+keepalive      https://www.cnblogs.com/liuyisai/ ...

  7. 小D课堂 - 新版本微服务springcloud+Docker教程_6-01 微服务网关介绍和使用场景

    笔记 第六章 微服务网关zuul开发实战 1.微服务网关介绍和使用场景     简介:讲解网关的作用和使用场景 (画图)          1)什么是网关         API Gateway,是系 ...

  8. springcloud使用Zuul构建微服务网关入门

    为什么要使用微服务网关 不同的微服务一般会经过不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求. 如果让客户端直接与各个微服务通信,会有以下的问题: 客户端会多次请求不同的微 ...

  9. springcloud(十)-Zuul微服务网关

    为什么要使用微服务网关 前面的文章我们介绍了,Eureka用于服务的注册于发现,Feign支持服务的调用以及均衡负载,Hystrix处理服务的熔断防止故障扩散,Spring Cloud Config服 ...

  10. 微服务网关哪家强?一文看懂Zuul, Nginx, Spring Cloud, Linkerd性能差异

      导语:API Gateway是实现微服务重要的组件之一.面对诸多的开源API Gateway,如何进行选择也是架构师需要关注的焦点.本文作者对几个较大的开源API Gateway进行了压力测试,对 ...

随机推荐

  1. STM32 定时器时钟配置技巧

    众所周知 STM32 的时钟配置比较复杂,而定时器的时钟配置更是 '奇葩'. 如下图(截图自STM32F4编程手册)APB的预分频器分频系数如果不为1,则定时器的时钟就倍频了反而. 配置技巧 下面以S ...

  2. git 忽略已提交(commit)的文件/文件夹

    git 忽略已提交的文件或文件夹 最好是在工程一开始就编辑好 .gitignore 文件, 在第一次提交的时候仔细检查避免添加那些无用的文件 因为 .gitignore 只能对未提交过的文件起效, 也 ...

  3. 递归+DP:爬楼梯问题

        一只青蛙一次可以跳上 1 级台阶,也可以跳上2 级.求该青蛙跳上一个n 级的台阶总共有多少种跳法. 输入格式: 首先输入数字n,代表接下来有n组输入,50>=n>=0,然后每行一个 ...

  4. JSX、TSX 整体理解

    可以少去理解一些不必要的概念,而多去思考为什么会有这样的东西,它解决了什么问题,或者它的运行机制是什么? JS JavaScript 是互联网上最流行的脚本语言,这门语言可用于 HTML 和 web, ...

  5. UIPath初识和安装

    即使没有人为你鼓掌,也要优雅的谢幕,感谢自己的认真付出. 一. UiPath组成   学习UiPath,我们一定先要了解Studio,Robot和Orchestrator这3个重要组成部分. UiPa ...

  6. 在路上---学习篇(一)Python 数据结构和算法 (1)

    数据结构和算法 现阶段的肤浅理解数据结构是各式各样的类型数据在内存中是如何构造的,原理是怎么样的. 了解了其本质后,在面对问题时候,根据数据结构利用算法计算可以最快,最有效的完成任务.通常情况下,精心 ...

  7. Flask SocketIO 实现动态绘图

    Flask-SocketIO 是基于 Flask 的一个扩展,用于简化在 Flask 应用中集成 WebSocket 功能.WebSocket 是一种在客户端和服务器之间实现实时双向通信的协议,常用于 ...

  8. 吉特日化MES-日化生产相关设备区分

    在化妆品生产过程中约到各种各样的设备,对日化生产设备做一些简单的整理汇总,便于学习(其中设备根据其所在的产品以及领域会有一定的不同) 从产品的角度可以将产品划分为: (1) 乳化剂类产品 (2) 分类 ...

  9. [ABC272G] Yet Another mod M

    Problem Statement You are given a sequence $A=(A_1,A_2,\dots,A_N)$ of length $N$ consisting of posit ...

  10. 【论文阅读】HTTP 流量和恶意 URL 的异常检测

    Part 1关于论文 基本信息 题目:HTTP 流量和恶意 URL 的异常检测 源码:sec2vec源代码 摘要 在本文中,我们将展示如何利用自然语言处理(NLP)中已知 的方法来检测 HTTP 请求 ...