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 R6 集群创建流复制只读副本库案例

    一.环境概述 [kingbase@node2 bin]$ ./ksql -U system test ksql (V8.0) Type "help" for help. test= ...

  2. Enable_hint_table 使用

    KingbaseES enable_hint_table 可以看成类似 oracle outline 工具,可以在不修改SQL 的情况下,通过hint 改变SQL 的执行计划. 一.启用enable_ ...

  3. 使用Kali的wifite和aircrack-ng联合破解wifi密码

    准备材料 有kali的虚拟机,这里推荐VM 一个超级便宜的USB无线网卡,很便宜三十几块钱 一个靠谱的WPA密码字典(关于字典文件,我这里整理了好多,可联系我.QQ:1213456261) 1.运行k ...

  4. RabbitMQ之消息模式简单易懂,超详细分享~~~

    前言 上一篇对RabbitMQ的流程和相关的理论进行初步的概述,如果小伙伴之前对消息队列不是很了解,那么在看理论时会有些困惑,这里以消息模式为切入点,结合理论细节和代码实践的方式一起来学习. 正文 常 ...

  5. 使用kubectl管理Kubernetes(k8s)集群:常用命令,查看负载,命名空间namespace管理

    目录 一.系统环境 二.前言 三.kubectl 3.1 kubectl语法 3.2 kubectl格式化输出 四.kubectl常用命令 五.查看kubernetes集群node节点和pod负载 5 ...

  6. 输入法词库解析(六)QQ 拼音分类词库.qpyd

    详细代码:https://github.com/cxcn/dtool 前言 .qpyd 是 QQ 拼音输入法 6.0 以下版本所用的词库格式,可以在 http://cdict.qq.pinyin.cn ...

  7. Python实验报告——第4章 序列的应用

    实验报告 [实验目的] 1.掌握python中序列及序列的常用操作. 2.根据实际需要选择使用合适的序列类型. [实验条件] 1.PC机或者远程编程环境. [实验内容] 1.完成第四章 序列的应用 实 ...

  8. Solutions:Elastic workplace 搜索:随时随地搜索所有内容 (二)

  9. kibana安装安装插件

    命令语法:bin/kibana-plugin install <package name or URL> 当您指定的插件名没有带 URL,插件工具将会尝试去下载 Elastic 官方插件. ...

  10. mac 批量修改文件的后缀名

    1-将需要修改的文件拖到同一个文件夹 2-打开终端输入 for i in *; do mv "$i" "$i.jpg";done