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 Hint 使用

    前言:KingbaseES V8R6C4 之前版本hint 使用方法是与Postgresql 相同的,通过 pg_hint_plan扩展,支持在SQL中使用hint.由于该版本的hint只能放置于SQ ...

  2. KingbaseES 转义字符

    在SQL标准中字符串是用单引号括起来的,在KingbaseES中遵守了该标准,如果在字符串中需要使用到单引号,就需要对其进行转义. 方式一:使用E和反斜杠进行转义 方式二:直接用一个单引号来转义 在K ...

  3. KingbaseES sys_prewarm 扩展

    Oracle 在查询数据 可以通过cache hint 所访问的数据cache 到数据库buffer,对于KingbaseES,如何将数据加载到cache 了?sys_prewarm 扩展插件可以实现 ...

  4. 水晶报表中用Code128制作条型码的方法

    一.在[文件系统]中新建一个[Fonts文件夹],然后添加[Code128.ttf]文件. 二.在水晶报表里的[字段资源管理器]的[公式字段]中新建一个公式字段.点击[使用编辑器]之后弹出[公式工作室 ...

  5. 史上最全的selenium三大等待介绍

    一.强制等待 1.设置完等待后不管有没有找到元素,都会执行等待,等待结束后才会执行下一步 2.实例 driver = webdriver.Chrome() driver.get("https ...

  6. Raft 共识算法

    转载请注明出处:https://www.cnblogs.com/morningli/p/16745294.html raft是一种管理复制日志的算法,raft可以分解成三个相对独立的子问题: 选主(L ...

  7. SpringBoot入门项目CRM学习过程中的报错记录(更新ing)

    在用mybatis自动生成实体类和mapper时报错..... is unrecognized or represents more than one time zone. You must conf ...

  8. IDEA生成带参数和返回值注释

    步骤说明 打开IDEA进入点击左上角 - 文件 - 设置 - 编辑器 - 活动模板 新建活动模板 填写模板文本 编辑变量 添加变量表达式 设置模板使用范围-设置全部范围应用-或者设置只在Java代码中 ...

  9. Docker | 容器互联互通

    上篇讲到创建自定义网络,我创建了 mynet 网络,并指定了网关和子网地址.在上篇结尾呢,我抛出了一个问题:其它网络下的容器可以直接访问mynet网络下的容器吗?今天就让我们一块看下怎么实现容器互联. ...

  10. 微信小程序专题(二)-----微信openid的获取

    一,简单来讲就是以下流程 通过get方式获取信息 在前端调用wx.login() 获取 临时登录凭证code之后,将code字符串发送给后端,后端通过auth.code2Session接口获取用户唯一 ...