# 简介

官网文档 4.6 (opens new window)

网关是系统唯一对外的入口,介于客户与服头器端之间,用子对请求进行鉴权、限流、路由、监控等功能。

DANGER

Spring Cloud Gateway is built on Spring Boot, Spring WebFlux, and Project Reactor. As a consequence, many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you know may not apply when you use Spring Cloud Gateway. If you are unfamiliar with these projects, we suggest you begin by reading their documentation to familiarize yourself with some new concepts before working with Spring Cloud Gateway.

译: Spring Cloud Gateway 构建于Spring Boot、Spring WebFlux和Project Reactor之上。因此,当您使用 Spring Cloud Gateway 时,您所知道的许多熟悉的同步库(例如 Spring Data 和 Spring Security)和模式可能不适用。如果您不熟悉这些项目,我们建议您在使用 Spring Cloud Gateway 之前首先阅读他们的文档以熟悉一些新概念。

DANGER

Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or when built as a WAR.

译: Spring Cloud Gateway 需要 Spring Boot 和 Spring Webflux 提供的 Netty 运行时。它不适用于传统的 Servlet 容器或构建为 WAR 时。

# 三个重要概念

# router 路由

路由是网关的最基本组成,由一个路由id、一个目标地址url,一组断言工厂及一组 filter 组成。若断言为true,则请求将经由filter被路由到目标url。

# predicate 断言

断言即一个条件判断,根据当前的http请求进行指定规则的匹配,比如说http请求头,请求时间等。
只有当匹配上规则时,断言才为true,此时请求才会被直接路由到目标地址(目标服务器),或先路由到某过滤器链,经过过滤器链的层层处理后,再路由到相应的目标地址(目标服务器)。

# filter 过滤器

对请求进行处理的逻辑部分。当请求的断言为true时,会被路由到设置好的过滤器,以对请求或响应进行处理。
例如,可以为请求添加一个请求参数,或对请求U!进行修改,或为响应添加header等。总之,就是对请求或响应进行处理。

# 依赖

引入了 gateway 依赖,就不要再引入 web 依赖,不然启动会报错

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