前言
spring gateway 是基于 spring framework 的 api 网关,它为微服务架构提供了路由、监控、弹性以及安全性等功能。spring gateway 使用非阻塞 api 和高性能的反应式编程模型来提供服务。
版本说明
本文的选项在多个最近的 spring cloud gateway 版本中都是有效的,比如 spring cloud 2020.0.x 至 2021.0.x 版本系列。与 spring boot 2.3.x 至 2.6.x 版本兼容。
基础配置
以下是一个完整的 spring gateway 配置示例,包含了常见的路由配置、过滤器使用、全局过滤器配置以及一些其他常用的设置。这些配置将在 application.yml
文件中进行设置:
spring:
cloud:
gateway:
# 路由配置列表
routes:
# 第一条路由规则
- id: route1
uri: http://example.org
predicates:
- path=/api/service1/** # 路径匹配规则
filters:
- addrequestheader=x-request-foo, bar # 添加请求头
# 第二条路由规则
- id: route2
uri: http://example.com
predicates:
- path=/api/service2/**
- method=get,post # 只允许 get 和 post 方法
filters:
- rewritepath=/api/service2/(?<segment>.*), /$\{segment} # url 重写
# 全局过滤器配置
default-filters:
- deduperesponseheader=access-control-allow-credentials access-control-allow-origin # 去重http响应头
# 用于控制 http 请求的负载均衡器配置
loadbalancer:
use404: true # 当无可用服务时返回404
# http请求重试配置
retry:
enabled: true
retries: 3 # 重试次数
statuses: bad_gateway,gateway_timeout # 触发重试的http状态码
methods: get,post # 允许重试的http方法
backoff:
firstbackoff: 50ms # 首次重试的延迟
maxbackoff: 500ms # 最大重试延迟
factor: 2 # 延迟因子
basedonpreviousvalue: false # 延迟是否基于上一次的延迟时间
# 跨域配置
globalcors:
corsconfigurations:
'[/**]':
allowedorigins: "*" # 允许所有域
allowedmethods: "*" # 允许所有方法
allowedheaders: "*" # 允许所有头
allowcredentials: true # 允许证书
# spring 应用名称
spring:
application:
name: gateway-service
# 服务端口
server:
port: 8080
# 日志配置
logging:
level:
org.springframework.cloud.gateway: debug # 设置spring gateway的日志级别为debug
在这个示例中,配置了两条路由规则,每条规则都设置了特定的路径匹配和过滤器。还配置了全局的过滤器,用于去重响应头。另外还包含了负载均衡器配置、重试机制以及全局跨域资源共享(cors)配置。
高级特性
spring cloud gateway 提供了丰富的配置选项来支持各种高级功能,包括但不限于过滤器自定义、安全性增强、限流、websocket 支持和更复杂的路由条件。
1. 安全配置
如果你需要将 spring security 集成到 spring cloud gateway 中,以增强 api 网关的安全性,你可以添加如下依赖并配置相应的安全规则:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-security</artifactid>
</dependency>
然后,你可以配置基本的 http 安全规则,如下所示:
@configuration
public class securityconfig extends websecurityconfigureradapter {
@override
protected void configure(httpsecurity http) throws exception {
http
.authorizerequests()
.antmatchers("/api/public/**").permitall()
.anyrequest().authenticated()
.and()
.httpbasic();
}
}
2. 限流策略
限流可以帮助你控制对后端服务的请求频率,防止过载。spring cloud gateway 可以通过集成 redis 来实现请求的限流:
spring:
cloud:
gateway:
routes:
- id: route1
uri: http://example.org
predicates:
- path=/api/service1/**
filters:
- name: requestratelimiter
args:
redis-rate-limiter.replenishrate: 10
redis-rate-limiter.burstcapacity: 20
3. websocket 支持
spring cloud gateway 支持 websocket 代理,需要适当的路由配置:
spring:
cloud:
gateway:
routes:
- id: websocket_route
uri: ws://example-websocket.org
predicates:
- path=/echo
4. 动态路由
在一些场景下,你可能需要动态地添加或删除路由。这可以通过编程方式实现,比如使用 routedefinitionwriter
和 applicationeventpublisher
:
@autowired
private routedefinitionwriter routewriter;
@autowired
private applicationeventpublisher publisher;
public void addroute(routedefinition routedefinition) {
routewriter.save(mono.just(routedefinition)).subscribe();
this.publisher.publishevent(new refreshroutesevent(this));
}
5. 熔断器配置
spring cloud gateway 集成了 resilience4j 来提供熔断器支持,可以配置熔断规则来保护后端服务:
spring:
cloud:
gateway:
routes:
- id: route1
uri: http://example.org
filters:
- name: circuitbreaker
args:
name: backendservice
fallbackuri: forward:/fallback
6. 跟踪和日志记录
为了更好地监控和诊断网关流量,可以集成 spring cloud sleuth 和 zipkin 进行调用链跟踪。这可以帮助你详细了解请求如何通过你的网关和服务。首先需要添加 sleuth 和 zipkin 的依赖:
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-starter-sleuth</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.cloud</groupid>
<artifactid>spring-cloud-sleuth-zipkin</artifactid>
</dependency>
配置 zipkin 的服务地址:
spring:
zipkin:
baseurl: http://localhost:9411
sleuth:
sampler:
probability: 1.0 # 采样率
7. 参数化路由匹配
spring cloud gateway 允许你根据请求参数、头信息等进行路由匹配。例如,你可以根据请求头中的版本号将流量路由到不同的后端服务:
spring:
cloud:
gateway:
routes:
- id: route1
uri: http://example.org/v1
predicates:
- path=/api/service
- header=x-api-version, v1
- id: route2
uri: http://example.org/v2
predicates:
- path=/api/service
- header=x-api-version, v2
8. 环境特定配置
在不同的环境(开发、测试、生产)中,你可能需要不同的配置。spring cloud gateway 允许你使用 spring 的 profile 功能来定义环境特定的配置。例如,你可以为开发环境和生产环境定义不同的路由和过滤器配置:
---
spring:
profiles: dev
cloud:
gateway:
routes:
- id: dev_route
uri: http://dev.example.org
predicates:
- path=/api/dev/**
---
spring:
profiles: prod
cloud:
gateway:
routes:
- id: prod_route
uri: http://prod.example.org
predicates:
- path=/api/prod/**
9. 响应重写
在某些情况下,你可能需要修改从后端服务返回的响应。spring cloud gateway 提供了过滤器来重写响应头和响应体:
spring:
cloud:
gateway:
routes:
- id: rewrite_response
uri: http://example.org
filters:
- modifyresponsebody=/path, ${{response.body}} modified
- modifyresponseheader=x-response-header, new-header-value
10. 自定义过滤器
如果预置的过滤器不能满足你的需求,你可以实现自己的过滤器。你可以继承 abstractgatewayfilterfactory
类来创建自定义的过滤器逻辑:
public class mycustomfilter extends abstractgatewayfilterfactory<mycustomfilter.config> {
public static class config {
// put the configuration properties for your filter here
}
@override
public gatewayfilter apply(config config) {
return (exchange, chain) -> {
// custom pre-processing
return chain.filter(exchange).then(mono.fromrunnable(() -> {
// custom post-processing
}));
};
}
}
继续探索 spring cloud gateway 的高级配置,这些配置可以进一步增强你的网关的功能性和灵活性。以下是一些额外的配置选项和高级用法,它们可以帮助你更好地适应复杂的业务需求:
11. hystrix 集成
虽然 resilience4j 是现代的断路器选择,但如果你的项目还在使用 hystrix,spring cloud gateway 也支持与 hystrix 的集成。你可以为特定路由添加 hystrix 保护:
spring:
cloud:
gateway:
routes:
- id: hystrix_route
uri: http://example.org
filters:
- name: hystrix
args:
name: mycommand
fallbackuri: forward:/fallback
12. 路由验证
在一些应用场景中,需要对请求进行额外的验证,比如检查请求中的 jwt 令牌。spring cloud gateway 允许通过全局过滤器或路由特定过滤器来实现这一点:
@bean
public routelocator customroutelocator(routelocatorbuilder builder) {
return builder.routes()
.route("token_route", r -> r.path("/token/**")
.filters(f -> f.filter(new authfilter()))
.uri("http://example.org"))
.build();
}
public class authfilter implements gatewayfilter {
@override
public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
// 实现验证逻辑
boolean isvalid = checkauthtoken(exchange.getrequest());
if (!isvalid) {
exchange.getresponse().setstatuscode(httpstatus.unauthorized);
return exchange.getresponse().setcomplete();
}
return chain.filter(exchange);
}
private boolean checkauthtoken(serverhttprequest request) {
// 验证逻辑
return true; // 假设总是有效
}
}
13. api 版本管理
你可以通过配置多个路由来支持不同版本的 api,以方便客户端调用最合适的服务版本:
spring:
cloud:
gateway:
routes:
- id: api_v1
uri: http://example.org/v1
predicates:
- path=/api/v1/**
- id: api_v2
uri: http://example.org/v2
predicates:
- path=/api/v2/**
14. 更多动态路由配置
spring cloud gateway 允许通过数据库或其他服务动态加载和更改路由配置。这可以通过自定义 routedefinitionlocator
实现:
@bean
public routedefinitionlocator databaseroutelocator() {
return new databaseroutedefinitionlocator();
}
public class databaseroutedefinitionlocator implements routedefinitionlocator {
@override
public flux<routedefinition> getroutedefinitions() {
// 从数据库加载路由定义
return flux.fromiterable(fetchroutesfromdatabase());
}
private list<routedefinition> fetchroutesfromdatabase() {
// 数据库操作,返回路由定义列表
return new arraylist<>();
}
}
15. 定制错误处理
你可以通过定义自己的 errorwebexceptionhandler
来定制网关在遇到错误时的行为:
@bean
@order(-1) // 确保它比默认的错误处理器优先级高
public errorwebexceptionhandler myexceptionhandler() {
return new jsonerrorwebexceptionhandler();
}
public class jsonerrorwebexceptionhandler implements errorwebexceptionhandler {
@override
public mono<void> handle(serverwebexchange exchange, throwable ex) {
exchange.getresponse().setstatuscode(httpstatus.bad_gateway);
// 设置响应体等
return exchange.getresponse().writewith(mono.just(...));
}
}
发表评论