在微服务架构中,服务网关扮演着至关重要的角色。它作为系统的统一入口,负责路由请求、鉴权、限流等功能。Spring Cloud Gateway 是 Spring 生态系统中一个基于 Spring WebFlux 构建的响应式、非阻塞的 API 网关。响应式编程模型使得它在处理高并发场景时具有更好的性能和资源利用率。本文将深入介绍 Spring Cloud Gateway 的使用,包括基本概念、配置、路由规则以及实际演示代码。
路由是 Spring Cloud Gateway 中最核心的概念之一。一个路由由 ID、目标 URI、断言(Predicate)和过滤器(Filter)组成。当请求满足断言条件时,会被路由到指定的目标 URI。
断言是 Java 8 中的 Predicate
函数式接口的扩展。它用于匹配 HTTP 请求的各种属性,如请求路径、请求方法、请求头等。只有当请求满足所有断言条件时,才会被路由。
过滤器可以对请求和响应进行修改。Spring Cloud Gateway 提供了两种类型的过滤器:全局过滤器和路由过滤器。全局过滤器会应用到所有路由上,而路由过滤器只应用到特定的路由上。
在开始使用 Spring Cloud Gateway 之前,需要创建一个 Spring Boot 项目,并添加相关依赖。在 pom.xml
中添加以下依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
同时,需要在 application.properties
或 application.yml
中配置 Spring Cloud Gateway 的相关信息。
在 application.yml
中配置一个简单的路由规则:
spring:
cloud:
gateway:
routes:
- id: example_route
uri: http://example.com
predicates:
- Path=/example/**
上述配置表示,当请求路径以 /example/
开头时,会被路由到 http://example.com
。
除了使用配置文件,还可以使用 Java 代码配置路由:
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("example_route", r -> r.path("/example/**")
.uri("http://example.com"))
.build();
}
}
以下是一个使用路由过滤器修改请求头的示例:
spring:
cloud:
gateway:
routes:
- id: header_route
uri: http://example.com
predicates:
- Path=/header/**
filters:
- AddRequestHeader=X-Request-Foo, Bar
上述配置表示,当请求路径以 /header/
开头时,会在请求头中添加一个名为 X-Request-Foo
,值为 Bar
的请求头。
全局过滤器会应用到所有路由上。以下是一个自定义全局过滤器的示例:
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Configuration
public class GlobalFilterConfig {
@Bean
public GlobalFilter customGlobalFilter() {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest().mutate()
.header("X-Global-Filter", "Global Filter Value")
.build();
ServerWebExchange newExchange = exchange.mutate().request(request).build();
return chain.filter(newExchange);
};
}
}
上述代码定义了一个全局过滤器,会在所有请求头中添加一个名为 X-Global-Filter
,值为 Global Filter Value
的请求头。
创建一个简单的 Spring Boot 服务,用于接收路由转发的请求:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class TargetServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TargetServiceApplication.class, args);
}
@GetMapping("/hello")
public String hello() {
return "Hello from Target Service!";
}
}
在 application.yml
中配置路由规则,将请求转发到上述服务:
spring:
cloud:
gateway:
routes:
- id: target_service_route
uri: http://localhost:8081
predicates:
- Path=/target/**
filters:
- RewritePath=/target/(?<segment>.*), /$\{segment}
上述配置表示,当请求路径以 /target/
开头时,会被路由到 http://localhost:8081
,并将请求路径中的 /target/
替换为空。
启动 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) | 可以对请求和响应进行修改,分为全局过滤器和路由过滤器 |