Spring-Cloud-Gateway

Spring-Cloud-Gateway


Spring Cloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。

Spring Cloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Netflix Zuul,其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。

相关概念:

  • Route(路由):这是网关的基本构建块。它由一个 ID,一个目标 URI,一组断言和一组过滤器定义如果断言为真,则路由匹配
  • Predicate(断言):这是一个 Java 8 的 Predicate。输入类型是一个 ServerWebExchange。我们可以使用它来匹配来自 HTTP 请求的任何内容,例如 headers 或参数。
  • Filter(过滤器):这是org.springframework.cloud.gateway.filter.GatewayFilter的实例,我们可以使用它修改请求和响应。


客户端向Spring Cloud Gateway 发出请求,如果Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway Web Handler。Handler再通过指定的过滤器链(多个过滤器组成过滤器链)来将请求发送到我们实际的服务执行业务逻辑,然后返回。

过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post”)执行业务逻辑。

Spring Cloud Gateway 的特征:

  • 基于 Spring Framework 5,Project Reactor 和 Spring Boot 2.0
  • 动态路由
  • Predicates 和 Filters 作用于特定路由
  • 集成 Hystrix 断路器
  • 集成 Spring Cloud DiscoveryClient
  • 易于编写的 Predicates 和 Filters
  • 限流
  • 路径重写

快速上手


Spring Cloud Gateway 网关路由有两种配置方式:

  • 在配置文件 yml 中配置
  • 通过@Bean自定义 RouteLocator,在启动主类 Application 中配置

这两种方式是等价的,建议使用yml方式进行配置

使用Spring Cloud Finchley 版本,Finchley版本依赖于Spring Boot 2.0.6.RELEASE。

pom文件

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.0.6.RELEASE</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependencyManagement>
  8. <dependencies>
  9. <dependency>
  10. <groupId>org.springframework.cloud</groupId>
  11. <artifactId>spring-cloud-dependencies</artifactId>
  12. <version>Finchley.SR2</version>
  13. <type>pom</type>
  14. <scope>import</scope>
  15. </dependency>
  16. </dependencies>
  17. </dependencyManagement>
  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter</artifactId>
  5. </dependency>
  6.   <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-starter-gateway</artifactId>
  9. </dependency>
  10. </dependencies>

Spring Cloud Gateway 是使用netty+webflux实现因此不需要再引入web模块

我们先测试一个最简单的请求转发

yml文件

  1. server:
  2. port: 8080
  3. spring:
  4. cloud:
  5. gateway:
  6. routes:
  7. - id: neo_route
  8. uri: https://spring.io/projects/spring-cloud
  9. predicates:
  10. - Path=/spring-cloud
  11. # id 我们自定义的路由ID 保持唯一 注意前面的-,切记不能省略
  12. # uri 目标服务地址
  13. # predicates(断言) 路由条件 predicate接受一个输入参数,返回一个布尔值结果,如果断言为真,则路由匹配
  14. #predicate 组合成其他复杂的逻辑
  15. #Path前面的-,切记不能省略

下面来一起看看效果:

访问localhost:8080/spring-cloud 跳转到https://spring.io/projects/spring-cloud

原文地址:https://blog.csdn.net/jYF_666/article/details/90765530
原文地址:https://www.cnblogs.com/jpfss/p/11944053.html