Spring Cloud Gateway 使用示例
Spring Cloud Gateway 使用示例
作者: Grey
原文地址:
CSDN:Spring Cloud Gateway 使用示例
说明
Spring Cloud Gateway 用于构建 API 网关,基于 Spring WebFlux。
在Spring Cloud G 版发布时,
Spring 官方把 Spring Cloud Gateway 作为 Zuul 1 的替代方案

本文主要通过一个示例介绍了 Spring Cloud Gateway 的基础使用。
环境
JDK 1.8+
Maven 3.5+
Spring Boot 版本:2.7.5
Spring Cloud 版本:2021.0.5
涉及的依赖包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
<scope>test</scope>
</dependency>
代码说明
第一个场景就是请求转发,例如
直接转到:http://jd.com:80/jd
请求:http://localhost:8080/greyzeng
直接转到:http://www.cnblogs.com/greyzeng
请求:http://localhost:8080/error
直接跳转到自定义的一个错误页面。
只需要做如下配置即可
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder, UriConfiguration uriConfiguration) {
return builder.routes()
.route(p -> p.path("/jd").uri("http://jd.com:80/"))
.route(p -> p.path("/greyzeng").uri("http://www.cnblogs.com/"))
.route(p -> p.path("/error").uri("forward:/fallback"))
.build();
}
@RequestMapping("/fallback")
public Mono<String> fallback() {
return Mono.just("fallback");
}
启动服务,运行 GatewayApplication.java
浏览器访问:http://localhost:8080/jd 和 http://localhost:8080/greyzeng,会直接跳转到对应的页面。
输入:http://localhost:8080/error,直接跳转到自定义的/fallback请求服务中。

在转发过程中,也可以设置一些参数,比如
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder, UriConfiguration uriConfiguration) {
final String httpUri = "http://httpbin.org:80";
return builder.routes()
.route(p -> p.path("/get").filters(f -> f.addRequestHeader("Hello", "World")).uri(httpUri))
.build();
}
在请求: http://localhost:8080/get 这个服务过程中,增加一个 Header 参数

第二个场景就是结合熔断器的使用,例如:Spring Cloud Circuit Breaker,过滤来自不同的 host 请求,比如,针对来自:*.circuitbreaker.com 的请求,将其转到统一的异常处理页面。
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder, UriConfiguration uriConfiguration) {
String httpUri = uriConfiguration.getHttpbin();
return builder.routes()
.route(p -> p.host("*.circuitbreaker.com").filters(f -> f.circuitBreaker(config -> config.setName("mycmd").setFallbackUri("forward:/fallback"))).uri(httpUri))
.build();
}
通过如下代码进行模拟测试,
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {"httpbin=http://localhost:${wiremock.server.port}"})
@AutoConfigureWireMock(port = 0)
public class GatewayApplicationTest {
@Autowired
private WebTestClient webClient;
@Test
public void contextLoads() {
//Stubs
stubFor(get(urlEqualTo("/delay/3")).willReturn(aResponse().withBody("no fallback").withFixedDelay(3000)));
webClient.get().uri("/delay/3").header("Host", "www.circuitbreaker.com").exchange().expectStatus().isOk().expectBody().consumeWith(response -> assertThat(response.getResponseBody()).isEqualTo("fallback".getBytes()));
}
}
简单说明一下
访问过程中,如果某个请求的 Host 来自于 www.circuitbreaker.com,会直接返回 /fallback 中。
如果 Host 不是 www.circuitbreaker.com,则直接返回正确结果即可。
完整代码
参考资料
Spring Cloud Gateway 使用示例的更多相关文章
- Spring Cloud Gateway服务网关
原文:https://www.cnblogs.com/ityouknow/p/10141740.html Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gatewa ...
- 网关服务Spring Cloud Gateway(三)
上篇文章介绍了 Gataway 和注册中心的使用,以及 Gataway 中 Filter 的基本使用,这篇文章我们将继续介绍 Filter 的一些常用功能. 修改请求路径的过滤器 StripPrefi ...
- 网关服务Spring Cloud Gateway(二)
上一篇文章服务网关 Spring Cloud GateWay 初级篇,介绍了 Spring Cloud Gateway 的相关术语.技术原理,以及如何快速使用 Spring Cloud Gateway ...
- 网关服务Spring Cloud Gateway(一)
Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gateway ,相比之前我们使用的 Zuul(1.x) 它有哪些优势呢?Zuul(1.x) 基于 Servlet,使 ...
- 微服务网关实战——Spring Cloud Gateway
导读 作为Netflix Zuul的替代者,Spring Cloud Gateway是一款非常实用的微服务网关,在Spring Cloud微服务架构体系中发挥非常大的作用.本文对Spring Clou ...
- 微服务网关 Spring Cloud Gateway
1. 为什么是Spring Cloud Gateway 一句话,Spring Cloud已经放弃Netflix Zuul了.现在Spring Cloud中引用的还是Zuul 1.x版本,而这个版本是 ...
- 跟我学SpringCloud | 第十二篇:Spring Cloud Gateway初探
SpringCloud系列教程 | 第十二篇:Spring Cloud Gateway初探 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich.SR1 如 ...
- 跟我学SpringCloud | 第十三篇:Spring Cloud Gateway服务化和过滤器
SpringCloud系列教程 | 第十三篇:Spring Cloud Gateway服务化和过滤器 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich. ...
- 跟我学SpringCloud | 第十四篇:Spring Cloud Gateway高级应用
SpringCloud系列教程 | 第十四篇:Spring Cloud Gateway高级应用 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich.SR1 ...
- Spring Cloud Gateway 服务网关快速上手
Spring Cloud Gateway 服务网关 API 主流网关有NGINX.ZUUL.Spring Cloud Gateway.Linkerd等:Spring Cloud Gateway构建于 ...
随机推荐
- 【面试题】JS使用parseInt()、正则截取字符串中数字
JS使用parseInt()和正则截取字符串中数字 点击打开视频讲解更加详细 parseInt() 函数 定义和用法 parseInt() 函数可解析一个字符串,并返回一个整数. 当参数 radix ...
- 放弃 Electron,拥抱 WebView2!JavaScript 快速开发独立 EXE 程序
Electron 不错,但也不是完美的. Electron 带来了很多优秀的桌面软件,但并不一定总是适合我们的需求. 多个选择总是好事! 我使用 Electron 遇到的一些麻烦 1.Electron ...
- WinForm完美实现Cefsharp-v49控件C#与JS交互,并且可加载运行flash
https://blog.csdn.net/zhao331863874/article/details/117328415
- day03-2无异常退出
多用户即时通讯系统03 4.编码实现02 4.3功能实现-无异常退出系统 4.3.1思路分析 上述代码运行时,在客户端选择退出系统的时候,可以发现程序并没有停止运行,原因是: 退出时,程序将循环标志l ...
- Kubernetes 监控--PromQL
Prometheus 通过指标名称(metrics name)以及对应的一组标签(label)唯一定义一条时间序列.指标名称反映了监控样本的基本标识,而 label 则在这个基本特征上为采集到的数据提 ...
- Beats:为 Beats => Logstash => Elasticsearch 架构创建 template 及 Dashboard
文章转载自:https://elasticstack.blog.csdn.net/article/details/115341977 前一段时间有一个开发者私信我说自己的 Beats 连接到 Logs ...
- .NET6 JWT(生成Token令牌)
一.Net 6环境下的.net core项目里如何使用JWT. 第一步,在Nuget引入JWT.Microsoft.AspNetCore.Authentication.JwtBearer这两个NuGe ...
- frp服务利用云主机docker服务实现Windows远程连接
1.云主机配置 1.docker部署 # 创建文件 mkdir -p /root/docker/frp && touch /root/docker/frp/frps.ini # 配置文 ...
- P1706 全排列问题 方法记录
原题链接 全排列问题 题目描述 按照字典序输出自然数 \(1\) 到 \(n\) 所有不重复的排列,即 \(n\) 的全排列,要求所产生的任一数字序列中不允许出现重复的数字. 输入格式 一个整数 \( ...
- Spring 深入——IoC 容器 01
IoC容器的实现学习--01 目录 IoC容器的实现学习--01 简介 IoC 容器系列的设计与实现:BeanFactory 和 ApplicationContext BeanFactory load ...