实验3:Spring Cloud Gateway 网关路由与鉴权实践
时间: 2025-07-02 20:24:27 浏览: 8
### Spring Cloud Gateway 路由与鉴权实践
#### 1. 路由规则配置
Spring Cloud Gateway 提供了一种灵活的方式来定义路由规则。通过 `application.yml` 文件可以轻松配置多个路由及其对应的断言条件。
以下是基于 YAML 的简单路由配置示例:
```yaml
spring:
cloud:
gateway:
routes:
- id: service01_route
uri: http://localhost:8081
predicates:
- Path=/service01/**
- id: service02_route
uri: http://localhost:8082
predicates:
- Path=/service02/**
```
此配置表示当请求路径以 `/service01/` 开头时,会将流量转发到 `http://localhost:8081`;同理,对于 `/service02/` 请求,则转发至 `http://localhost:8082`[^3]。
---
#### 2. 自定义 Filter 实现鉴权功能
为了实现更复杂的业务逻辑(如鉴权),可以通过自定义全局过滤器或局部过滤器来完成。下面是一个简单的 API 密钥验证的示例代码。
##### 全局过滤器 (GlobalFilter)
```java
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;
@Configuration
public class AuthFilterConfig {
@Bean
public GlobalFilter authFilter() {
return (exchange, chain) -> {
String apiKey = exchange.getRequest().getQueryParams().getFirst("api_key");
if ("valid_api_key".equals(apiKey)) { // 这里可以根据实际需求替换为数据库校验或其他方式
return chain.filter(exchange);
} else {
exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
return Mono.empty();
}
};
}
}
```
在此示例中,如果请求参数中未携带有效的 `api_key` 或者其值不正确,则返回 HTTP 状态码 401 Unauthorized[^2]。
---
#### 3. 局部过滤器 (GatewayFilter)
除了全局过滤器外,还可以针对特定路由应用局部过滤器。例如,在某个服务调用前添加日志记录或者修改请求头信息。
```java
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class CustomGatewayFilter implements org.springframework.cloud.gateway.filter.GatewayFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("CustomGatewayFilter executed...");
// 修改响应头部信息作为测试用途
ServerWebExchange modifiedExchange = exchange.mutate()
.response(response -> response.getHeaders().add("X-Custom-Header", "Value"))
.build();
return chain.filter(modifiedExchange);
}
}
```
然后可以在对应路由下指定该过滤器的应用范围:
```yaml
spring:
cloud:
gateway:
routes:
- id: custom_filter_service
uri: http://localhost:9000
filters:
- name: CustomGatewayFilter
args: {}
predicates:
- Path=/custom-filter-service/**
```
---
#### 4. 网关限流机制
在高并发环境下,合理设置限流策略能够有效保护下游服务免受过载影响。借助 Redis 和 Resilience4j 可以快速搭建一套分布式环境下的限流方案。
以下展示了一个基本的时间窗口计数器模型:
```java
@Bean
public RouteLocator routeLocator(GatewayConfigurationProperties properties,
RateLimiter rateLimiter) {
return new RouteLocatorBuilder().routes()
.route(r -> r.path("/rate-limited/**")
.filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(rateLimiter)))
.uri(properties.getDefaultUri()))
.build();
}
// 定义速率限制器 bean
@Bean
public RateLimiter<Object> requestRateLimiter(RedisTemplate<String, Object> redisTemplate) {
FixedWindowRateLimiter limiter = new FixedWindowRateLimiter(60); // 每分钟最多允许访问次数
return () -> limiter.isAllowed(redisTemplate.opsForValue());
}
```
以上代码片段展示了如何利用固定时间窗算法控制每秒内的最大请求数量[^4]。
---
### 总结
本文介绍了 Spring Cloud Gateway 中关于路由和鉴权的核心概念,并提供了若干实用案例帮助开发者理解其实现细节。无论是基础的功能还是高级特性都可以通过调整配置文件以及编写适当 Java 类型对象加以满足。
阅读全文
相关推荐


















