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. Order Siblings by 排序

    在层次查询中,如果想让"亲兄弟"按规矩进行升序排序就需要使用ORDER SIBLINGS BY 这个特定的排序语句,若要降序输出可以在其后添加DESC关键字. 通过这个实验给大家展 ...

  2. KingbaseES R3 受限dba影响集群切换

    ​ 一.受限dba功能说明(参考自官方文档) 受限DBA 受限DBA可以对当前DBA的权限进行一定限制.当功能开启后DBA将不能更改以下对象: Table Database Function(by n ...

  3. [Python]-pandas模块-机器学习Python入门《Python机器学习手册》-02-加载数据:加载文件

    <Python机器学习手册--从数据预处理到深度学习> 这本书类似于工具书或者字典,对于python具体代码的调用和使用场景写的很清楚,感觉虽然是工具书,但是对照着做一遍应该可以对机器学习 ...

  4. Kubernetes实践技巧:资源预留

    ubernetes 的节点可以按照节点的资源容量进行调度,默认情况下 Pod 能够使用节点全部可用容量.这样就会造成一个问题,因为节点自己通常运行了不少驱动 OS 和 Kubernetes 的系统守护 ...

  5. 使用nginx反向代理RabbitMQ的web界面

    直接贴nginx的conf配置: server { listen 80; server_name www.xxxxx.com; location / { client_body_buffer_size ...

  6. 使用supervisor管理tomcat,nginx等进程详解

    1,介绍 官网:http://supervisord.org Supervisor是用Python开发的一套通用的进程管理程序,能将一个普通的命令行进程变为后台daemon,并监控进程状态,异常退出时 ...

  7. Spring Boot 使用 Micrometer 集成 Prometheus 监控 Java 应用性能

    转载自:https://cloud.tencent.com/developer/article/1508319 文章目录1.Micrometer 介绍2.环境.软件准备3.Spring Boot 工程 ...

  8. netstat -lnp |grep XXX后不显示进程

    netstat -lnp |grep XXX后不显示进程,不一定是没有进程,可能是这个命令不好使,换成 ps -ef | grep XXX

  9. C++面向对象编程之复合、委托和继承

    1.复合,表示has a template <typename T> calss A{ protected: B<T> c; } 这里表示 A 里面有一个 B,A 可以调用 B ...

  10. Spring_Boot项目集成Swagger填坑

    事情是这样的: 最近疫情在家里闲的无聊 看了看Swagger-2 在练习的过程出现了错误 写个帖子 希望跟我有同样问题的朋友可以避雷. 下面进入正题: 编辑 我使用的swagger-2版本是2.9.4 ...