微信登录

服务网关 - Spring Cloud Gateway - 响应式网关

服务网关 - Spring Cloud Gateway - 响应式网关

一、引言

在微服务架构中,服务网关扮演着至关重要的角色。它作为系统的统一入口,负责路由请求、鉴权、限流等功能。Spring Cloud Gateway 是 Spring 生态系统中一个基于 Spring WebFlux 构建的响应式、非阻塞的 API 网关。响应式编程模型使得它在处理高并发场景时具有更好的性能和资源利用率。本文将深入介绍 Spring Cloud Gateway 的使用,包括基本概念、配置、路由规则以及实际演示代码。

二、Spring Cloud Gateway 基本概念

2.1 路由(Route)

路由是 Spring Cloud Gateway 中最核心的概念之一。一个路由由 ID、目标 URI、断言(Predicate)和过滤器(Filter)组成。当请求满足断言条件时,会被路由到指定的目标 URI。

2.2 断言(Predicate)

断言是 Java 8 中的 Predicate 函数式接口的扩展。它用于匹配 HTTP 请求的各种属性,如请求路径、请求方法、请求头等。只有当请求满足所有断言条件时,才会被路由。

2.3 过滤器(Filter)

过滤器可以对请求和响应进行修改。Spring Cloud Gateway 提供了两种类型的过滤器:全局过滤器和路由过滤器。全局过滤器会应用到所有路由上,而路由过滤器只应用到特定的路由上。

三、环境准备

在开始使用 Spring Cloud Gateway 之前,需要创建一个 Spring Boot 项目,并添加相关依赖。在 pom.xml 中添加以下依赖:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-gateway</artifactId>
  5. </dependency>
  6. </dependencies>

同时,需要在 application.propertiesapplication.yml 中配置 Spring Cloud Gateway 的相关信息。

四、配置路由规则

4.1 使用配置文件配置路由

application.yml 中配置一个简单的路由规则:

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: example_route
  6. uri: http://example.com
  7. predicates:
  8. - Path=/example/**

上述配置表示,当请求路径以 /example/ 开头时,会被路由到 http://example.com

4.2 使用 Java 代码配置路由

除了使用配置文件,还可以使用 Java 代码配置路由:

  1. import org.springframework.cloud.gateway.route.RouteLocator;
  2. import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. @Configuration
  6. public class GatewayConfig {
  7. @Bean
  8. public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
  9. return builder.routes()
  10. .route("example_route", r -> r.path("/example/**")
  11. .uri("http://example.com"))
  12. .build();
  13. }
  14. }

五、过滤器的使用

5.1 路由过滤器

以下是一个使用路由过滤器修改请求头的示例:

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: header_route
  6. uri: http://example.com
  7. predicates:
  8. - Path=/header/**
  9. filters:
  10. - AddRequestHeader=X-Request-Foo, Bar

上述配置表示,当请求路径以 /header/ 开头时,会在请求头中添加一个名为 X-Request-Foo,值为 Bar 的请求头。

5.2 全局过滤器

全局过滤器会应用到所有路由上。以下是一个自定义全局过滤器的示例:

  1. import org.springframework.cloud.gateway.filter.GlobalFilter;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.core.Ordered;
  5. import org.springframework.http.server.reactive.ServerHttpRequest;
  6. import org.springframework.web.server.ServerWebExchange;
  7. import reactor.core.publisher.Mono;
  8. @Configuration
  9. public class GlobalFilterConfig {
  10. @Bean
  11. public GlobalFilter customGlobalFilter() {
  12. return (exchange, chain) -> {
  13. ServerHttpRequest request = exchange.getRequest().mutate()
  14. .header("X-Global-Filter", "Global Filter Value")
  15. .build();
  16. ServerWebExchange newExchange = exchange.mutate().request(request).build();
  17. return chain.filter(newExchange);
  18. };
  19. }
  20. }

上述代码定义了一个全局过滤器,会在所有请求头中添加一个名为 X-Global-Filter,值为 Global Filter Value 的请求头。

六、实际演示代码

6.1 创建一个简单的 Spring Boot 服务

创建一个简单的 Spring Boot 服务,用于接收路由转发的请求:

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @SpringBootApplication
  6. @RestController
  7. public class TargetServiceApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(TargetServiceApplication.class, args);
  10. }
  11. @GetMapping("/hello")
  12. public String hello() {
  13. return "Hello from Target Service!";
  14. }
  15. }

6.2 配置 Spring Cloud Gateway

application.yml 中配置路由规则,将请求转发到上述服务:

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: target_service_route
  6. uri: http://localhost:8081
  7. predicates:
  8. - Path=/target/**
  9. filters:
  10. - RewritePath=/target/(?<segment>.*), /$\{segment}

上述配置表示,当请求路径以 /target/ 开头时,会被路由到 http://localhost:8081,并将请求路径中的 /target/ 替换为空。

6.3 测试

启动 TargetServiceApplication 和 Spring Cloud Gateway 应用程序,然后访问 http://localhost:8080/target/hello,应该会看到返回结果 Hello from Target Service!

七、总结

Spring Cloud Gateway 是一个功能强大的响应式 API 网关,它提供了丰富的路由规则和过滤器机制,可以满足各种复杂的微服务架构需求。通过本文的介绍和演示代码,相信你已经对 Spring Cloud Gateway 有了更深入的了解。在实际项目中,可以根据具体需求灵活配置路由和过滤器,提高系统的性能和安全性。

概念 描述
路由(Route) 由 ID、目标 URI、断言和过滤器组成,用于将请求路由到指定的目标 URI
断言(Predicate) 用于匹配 HTTP 请求的各种属性,只有满足断言条件的请求才会被路由
过滤器(Filter) 可以对请求和响应进行修改,分为全局过滤器和路由过滤器