Spring Cloud Gateway 使用示例

作者: Grey

原文地址:

博客园:Spring Cloud Gateway 使用示例

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://localhost:8080/jd

直接转到: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/jdhttp://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-usage

参考资料

Spring Cloud Gateway

Building a Gateway

重新定义 Spring Cloud 实战

Spring Cloud Gateway 使用示例的更多相关文章

  1. Spring Cloud Gateway服务网关

    原文:https://www.cnblogs.com/ityouknow/p/10141740.html Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gatewa ...

  2. 网关服务Spring Cloud Gateway(三)

    上篇文章介绍了 Gataway 和注册中心的使用,以及 Gataway 中 Filter 的基本使用,这篇文章我们将继续介绍 Filter 的一些常用功能. 修改请求路径的过滤器 StripPrefi ...

  3. 网关服务Spring Cloud Gateway(二)

    上一篇文章服务网关 Spring Cloud GateWay 初级篇,介绍了 Spring Cloud Gateway 的相关术语.技术原理,以及如何快速使用 Spring Cloud Gateway ...

  4. 网关服务Spring Cloud Gateway(一)

    Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gateway ,相比之前我们使用的 Zuul(1.x) 它有哪些优势呢?Zuul(1.x) 基于 Servlet,使 ...

  5. 微服务网关实战——Spring Cloud Gateway

    导读 作为Netflix Zuul的替代者,Spring Cloud Gateway是一款非常实用的微服务网关,在Spring Cloud微服务架构体系中发挥非常大的作用.本文对Spring Clou ...

  6. 微服务网关 Spring Cloud Gateway

    1.  为什么是Spring Cloud Gateway 一句话,Spring Cloud已经放弃Netflix Zuul了.现在Spring Cloud中引用的还是Zuul 1.x版本,而这个版本是 ...

  7. 跟我学SpringCloud | 第十二篇:Spring Cloud Gateway初探

    SpringCloud系列教程 | 第十二篇:Spring Cloud Gateway初探 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich.SR1 如 ...

  8. 跟我学SpringCloud | 第十三篇:Spring Cloud Gateway服务化和过滤器

    SpringCloud系列教程 | 第十三篇:Spring Cloud Gateway服务化和过滤器 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich. ...

  9. 跟我学SpringCloud | 第十四篇:Spring Cloud Gateway高级应用

    SpringCloud系列教程 | 第十四篇:Spring Cloud Gateway高级应用 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich.SR1 ...

  10. Spring Cloud Gateway 服务网关快速上手

    Spring Cloud Gateway 服务网关 API 主流网关有NGINX.ZUUL.Spring Cloud Gateway.Linkerd等:Spring Cloud Gateway构建于 ...

随机推荐

  1. KingbaseES V8R3集群管理维护案例之---集群迁移单实例架构

    案例说明: 在生产中,需要将KingbaseES V8R3集群转换为单实例架构,可以采用以下方式快速完成集群架构的迁移. 适用版本: KingbaseES V8R3 当前数据库版本: TEST=# s ...

  2. KingbaseES 绑定变量窥探机制

    概述: 对于数据严重倾斜的,极端如以下例子,不同的传入值,可能执行计划不同,制定执行计划时,就要求知道变量的值.对于绑定变量的情况,我们知道Oracle 有 _optim_peek_user_bind ...

  3. 字节跳动 DanceCC 工具链系列之Xcode LLDB耗时监控统计方案

    作者:李卓立 仲凯宁 背景介绍 在<字节跳动 DanceCC 工具链系列之Swift 调试性能的优化方案>[1]一文中,我们介绍了如何使用自定义的工具链,来针对性优化调试器的性能,解决大型 ...

  4. 动态调整日志级别思路&实现

    引言 上篇文章 性能调优--小小的 log 大大的坑 已将详细的介绍了高并发下,不正确的使用日志姿势,可能会导致服务性能急剧下降问题.文末也给各位留下了解决方案--日志级别动态调整. 本文将详细介绍& ...

  5. Oracle PLM,协同研发的产品生命周期管理平台

    官网:Oracle PLM - 方正璞华 适用企业:电子高科技.机械制造.医疗器械.化工行业等大型企业和中小型企业 咨询热线:4006-160-730 申请试用.预约演示.产品询价 邮箱:jiangc ...

  6. Elastic:为Elasticsearch启动https访问

  7. 第三章:模版层 - 1:Django模板语言详解

    本节将介绍Django模版系统的语法.Django模版语言致力于在性能和简单性上取得平衡. 如果你有过其它编程背景,或者使用过一些在HTML中直接混入程序代码的语言,那么你需要记住,Django的模版 ...

  8. 使用logstash同步Mysql数据表到ES的一点感悟

    针对单独一个数据表而言,大致可以分如下两种情况: 1.该数据表中有一个根据当前时间戳更新的字段,此时监控的是这个时间戳字段 具体可以看这个文章:https://www.cnblogs.com/sand ...

  9. python中限定导入的子模块

    如果包定义文件__init__.py中存在一个叫做__all__的列表变量,那么在使用from package import *的时候就把这个列表中的所有名字作为要导入的模块名. 例如在example ...

  10. 内网横向渗透 之 ATT&CK系列一 之 信息收集

    前言 靶机下载地址:ATT&CK 拓扑图: 通过模拟真实环境搭建的漏洞靶场,完全模拟ATK&CK攻击链路进行搭建,形成完整个闭环.虚拟机默认密码为hongrisec@2019. 环境搭 ...