在本文中,我们着眼于为 Spring Cloud Gateway 编写自定义扩展。在开始之前,让我们回顾一下 Spring Cloud Gateway 的工作原理:
- 首先,客户端向网关发出网络请求
- 网关定义了许多路由,每个路由都有谓词来匹配请求和路由。例如,您可以匹配 URL 的路径段或请求的 HTTP 方法。
- 一旦匹配,网关对应用于路由的每个过滤器执行预请求逻辑。例如,您可能希望将查询参数添加到您的请求中
- 代理过滤器将请求路由到代理服务
- 服务执行并返回响应
- 网关接收响应并在返回响应之前对每个过滤器执行请求后逻辑。例如,您可以在返回客户端之前删除不需要的响应标头。
我们的扩展将对请求正文进行哈希处理,并将该值添加为名为 的请求标头X-Hash。这对应于上图中的步骤 3。注意:当我们读取请求正文时,网关将受到内存限制。
首先,我们在 start.spring.io 中创建一个具有 Gateway 依赖项的项目。在此示例中,我们将在 Java 中使用带有 JDK 17 和 Spring Boot 2.7.3 的 Gradle 项目。下载、解压缩并在您喜欢的 IDE 中打开项目并运行它,以确保您已为本地开发做好准备。
接下来让我们创建 GatewayFilter Factory,它是一个限定于特定路由的过滤器,它允许我们以某种方式修改传入的 HTTP 请求或传出的 HTTP 响应。在我们的例子中,我们将使用附加标头修改传入的 HTTP 请求:
<b>package</b> com.example.demo; <b>import</b> java.security.MessageDigest; <b>import</b> java.security.NoSuchAlgorithmException; <b>import</b> java.util.Collections; <b>import</b> java.util.List; <b>import</b> org.bouncycastle.util.encoders.Hex; <b>import</b> reactor.core.publisher.Mono; <b>import</b> org.springframework.cloud.gateway.filter.GatewayFilter; <b>import</b> org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; <b>import</b> org.springframework.cloud.gateway.support.ServerWebExchangeUtils; <b>import</b> org.springframework.http.codec.HttpMessageReader; <b>import</b> org.springframework.http.server.reactive.ServerHttpRequest; <b>import</b> org.springframework.stereotype.Component; <b>import</b> org.springframework.util.Assert; <b>import</b> org.springframework.web.reactive.function.server.HandlerStrategies; <b>import</b> org.springframework.web.reactive.function.server.ServerRequest; <b>import</b> <b>static</b> org.springframework.cloud.gateway.support.ServerWebExchangeUtils.CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR; <font><i>/** * This filter hashes the request body, placing the value in the X-Hash header. * Note: This causes the gateway to be memory constrained. * Sample usage: RequestHashing=SHA-256 */</i></font><font> @Component <b>public</b> <b>class</b> RequestHashingGatewayFilterFactory <b>extends</b> AbstractGatewayFilterFactory<RequestHashingGatewayFilterFactory.Config> { <b>private</b> <b>static</b> <b>final</b> String HASH_ATTR = </font><font>"hash"</font><font>; <b>private</b> <b>static</b>