Spring Gateway 网关常见配置说明

前言

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: route1uri: http://example.orgpredicates:- Path=/api/service1/**  # 路径匹配规则filters:- AddRequestHeader=X-Request-Foo, Bar  # 添加请求头# 第二条路由规则- id: route2uri: http://example.compredicates:- 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: trueretries: 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 {@Overrideprotected 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: route1uri: http://example.orgpredicates:- Path=/api/service1/**filters:- name: RequestRateLimiterargs:redis-rate-limiter.replenishRate: 10redis-rate-limiter.burstCapacity: 20

3. WebSocket 支持

Spring Cloud Gateway 支持 WebSocket 代理,需要适当的路由配置:

spring:cloud:gateway:routes:- id: websocket_routeuri: ws://example-websocket.orgpredicates:- Path=/echo

4. 动态路由

在一些场景下,你可能需要动态地添加或删除路由。这可以通过编程方式实现,比如使用 RouteDefinitionWriterApplicationEventPublisher

@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: route1uri: http://example.orgfilters:- name: CircuitBreakerargs:name: backendServicefallbackUri: 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:9411sleuth:sampler:probability: 1.0  # 采样率

7. 参数化路由匹配

Spring Cloud Gateway 允许你根据请求参数、头信息等进行路由匹配。例如,你可以根据请求头中的版本号将流量路由到不同的后端服务:

spring:cloud:gateway:routes:- id: route1uri: http://example.org/v1predicates:- Path=/api/service- Header=X-API-Version, v1- id: route2uri: http://example.org/v2predicates:- Path=/api/service- Header=X-API-Version, v2

8. 环境特定配置

在不同的环境(开发、测试、生产)中,你可能需要不同的配置。Spring Cloud Gateway 允许你使用 Spring 的 profile 功能来定义环境特定的配置。例如,你可以为开发环境和生产环境定义不同的路由和过滤器配置:

---
spring:profiles: devcloud:gateway:routes:- id: dev_routeuri: http://dev.example.orgpredicates:- Path=/api/dev/**---
spring:profiles: prodcloud:gateway:routes:- id: prod_routeuri: http://prod.example.orgpredicates:- Path=/api/prod/**

9. 响应重写

在某些情况下,你可能需要修改从后端服务返回的响应。Spring Cloud Gateway 提供了过滤器来重写响应头和响应体:

spring:cloud:gateway:routes:- id: rewrite_responseuri: http://example.orgfilters:- 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}@Overridepublic GatewayFilter apply(Config config) {return (exchange, chain) -> {// custom pre-processingreturn 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_routeuri: http://example.orgfilters:- name: Hystrixargs:name: myCommandfallbackUri: 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 {@Overridepublic 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_v1uri: http://example.org/v1predicates:- Path=/api/v1/**- id: api_v2uri: http://example.org/v2predicates:- Path=/api/v2/**

14. 更多动态路由配置

Spring Cloud Gateway 允许通过数据库或其他服务动态加载和更改路由配置。这可以通过自定义 RouteDefinitionLocator 实现:

@Bean
public RouteDefinitionLocator databaseRouteLocator() {return new DatabaseRouteDefinitionLocator();
}public class DatabaseRouteDefinitionLocator implements RouteDefinitionLocator {@Overridepublic 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 {@Overridepublic Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {exchange.getResponse().setStatusCode(HttpStatus.BAD_GATEWAY);// 设置响应体等return exchange.getResponse().writeWith(Mono.just(...));}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/829024.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python5

python应用实例 0.python基础1. python获取文件夹下所有文件的两种方式方法一&#xff1a;递归方法二&#xff1a;os.walk()&#xff08;推荐&#xff09; 2. python 读写csv文件写入读取 3. python 读写xml文件 0.python基础 python基础1 python基础2 python基础3 python基础…

C语言进阶:进阶指针(下)

一、 函数指针数组 我们都知道 数组是一个存放相同类型数据的存储空间 那我们已经学习了指针数组 那么函数有没有对应的指针数组呢&#xff1f; 如果有那应该怎么定义呢&#xff1f; 1. 函数指针数组的定义 我们说 函数指针数组的定义 应该遵循以下格式 int (*p[10])(); 首…

SpringBoot Aop使用篇

Getting Started SpringBoot AOP的实践 AOP相关的概念&#xff1a; Aspect&#xff08;切面&#xff09;&#xff1a; Aspect 声明类似于 Java 中的类声明&#xff0c;在 Aspect 中会包含着一些 Pointcut 以及相应的 Advice。就是抽离出来的逻辑类&#xff0c;比如日志、权限…

通过鼠标移入移出增加页面交互效果

有时候希望给用户带来一些炫酷的交互体验&#xff0c;常常会通过鼠标触发一些动态的样式效果&#xff01;&#xff01;&#xff01;这里简单总结一下&#xff0c;以后会不定时补充&#xff0c;谨以此博客作为记录&#xff01; 增加边框阴影 有时候加一点阴影的效果&#xff0c…

设计模式-行为型模式-观察者模式

观察者模式用于定义对象间的一种一对多的依赖关系&#xff0c;使得当一个对象状态变化时&#xff0c;其所有依赖对象都会收到通知并自动更新 /*** 行为型模式--观察者模式* 观察者模式用于定义对象间的一种一对多的依赖关系&#xff0c;使得当一个对象状态变化时&#xff0c;其…

C++及QT的线程学习

目录 一. 线程学习 二. 学习线程当中&#xff0c;得到的未知。 1. 了解以下MainWindow和main的关系 2. []()匿名函数 有函数体&#xff0c;没有函数名. 3. join和detach都是用来管理线程的生命周期的&#xff0c;它们的区别在于线程结束和资源的回收。 4. operator()() 仿…

4G组网三相四线预付费电表-远程集中抄表

安科瑞薛瑶瑶18701709087/17343930412 DTSY1352 三相预付费电能表分别用于计量额定频率50Hz 的单、三相交流有功电能&#xff0c;具有预付费控制、负载控制、时间控制及 RS485 通信等功能&#xff0c;性能指标符合 GB/T17215.321-2008 标准。是改革传统用电体制&#xff0c…

杰理695的UI模式LED灯控制

UI模式LED灯修改每个模式对应的LED灯闪烁修改在ui_normal_status_deal(u8 *status, u8 *power_status, u8 ui_mg_para)

开源克隆声音的项目-OpenVoice V2

myshell的OpenVoice 出v2版本了 只需要上传一段20秒到5分钟之间的声音&#xff0c;就可以克隆声音。 单人讲话 没有背景噪音 时间在20秒至5分钟之间 本地部署我没有做&#xff0c;我在myshell的官网上测试了一下&#xff0c;可能是上传的音频有杂音&#xff0c;导致不是很清…

设计模式- 迭代器模式(Iterator Pattern)结构|原理|优缺点|场景|示例

迭代器模式&#xff08;Iterator Pattern&#xff09;是一种行为设计模式&#xff0c;它提供了一种方法来顺序访问聚合对象&#xff08;容器&#xff09;中的元素&#xff0c;而又不暴露其实现细节。通过使用迭代器&#xff0c;用户可以从不同类型的聚合对象中以统一的方式遍历…

人机交互系统文本分类 text classification环节源码(E-commerce)

我把pre-trained model 下载到了本地 效果如下&#xff08;到时候把代码中的sequence 和labels换成自己的text和分类就行了。&#xff09;&#xff1a; 源码见链接&#xff1a; https://download.csdn.net/download/qqqweiweiqq/89211553

2024年好用又便宜的云手机!哪款性价比高?

随着科技的飞速发展&#xff0c;云计算技术也在不断演进&#xff0c;而云手机作为其创新之一&#xff0c;已经开始在我们的生活中崭露头角。它通过将手机的硬件和软件功能移到云端&#xff0c;让用户能够借助强大的云计算资源完成各种任务。2024年&#xff0c;哪款云手机性价比…

Ubuntu关闭防火墙、关闭selinux、关闭swap

关闭防火墙 打开终端&#xff0c;然后输入如下命令&#xff0c;查看防火墙状态&#xff1a; sudo ufw status 开启防火墙命令如下&#xff1a; sudo ufw enable 关闭防火墙命令如下&#xff1a; sudo ufw disable 关闭selinux setenforce 0 && sed -i s/SELINUXe…

QML中使用正则表达式

我想在TextField控件中使用正则表达式&#xff0c;然后GPT4给出的回答是这样的&#xff1a; TextField {id: versionInputplaceholderText: qsTr("输入版本号")validator: RegExpValidator { regExp: /^[a-zA-Z0-9]*$/ } // 仅允许字母和数字width: 120 // 设置合…

SpringBoot中多数据源灵活切换解决方案

本篇内容介绍了“SpringBoot中如何使用Dynamic Datasource配置多数据源”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成! 源码地址/文档说明 功能特性: 支持 数据源分组…

软件设计师-重点的创建型设计模式

一、简单工厂&#xff1a; 简单工厂模式属于创建型模式&#xff0c;但不属于23种设计模式之一。 软考中图 二、工厂方法&#xff1a; 意图&#xff1a; 定义一个用于创建对象的接口&#xff0c;让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。 结…

YOLOV5 TensorRT部署 BatchedNMS(engine模型推理)(下)

主要是在王新宇代码的基础上改进,引入对BatchedNMS的解码 文章目录 1. 修改yolov5.cpp2.修改yololayer.h1. 修改yolov5.cpp 首先增加全局变量,名字根据转onnx时修改的节点名字来,查看onnx文件可以看到,顺序不要弄错。 const char *INPUT_NAME = “images”; const char …

DDR3 MIG IP核解决方案

DDR3 MIG IP核解决方案 信号方向描述app_addr [ADDR_WIDTH - 1&#xff1a;0]输入该输入指示当前请求的地址。app_cmd [2&#xff1a;0]输入该输入选择当前请求的命令。app_en输入这是app_addr []&#xff0c;app_cmd [2&#xff1a;0]&#xff0c;app_sz和app_hi_pri输入的高…

Java自带的栈和队列(使用巨方便)

目录 1.Java封装的栈 2.Java自带的队列 2.1 ArrayDeque 2.2 LinkedList 2.3 PriorityQueue 1.Java封装的栈 栈——“后进先出”原则 Stack<T> stack new Stack();/**栈顶添加元素*/ stack.push(T);/**栈顶弹出元素*/ T temp stack.pop();/**查看当前栈顶元素,元素…

FFmpeg常用结构体、关键函数、ffplay.c分析

一、常用结构体&#xff1a; 1、AVFormatContext结构体&#xff1a; AVFormatContext是一个贯穿全局的数据结构&#xff0c;很多函数都要用它作为参数。FFmpeg代码中对这个数据结构的注释是format I/O context&#xff0c;此结构包含了一个视频流的格式内容。其中存有AVIputFor…