Exploring the New Spring Cloud Gateway – 探索新的Spring Cloud Gateway

最后修改: 2017年 10月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll explore the main features of the Spring Cloud Gateway project, a new API based on Spring 5, Spring Boot 2 and Project Reactor.

在本教程中,我们将探讨Spring Cloud Gateway项目的主要功能,这是一个基于Spring 5、Spring Boot 2和Project Reactor的新API。

The tool provides out-of-the-box routing mechanisms often used in microservices applications as a way of hiding multiple services behind a single facade.

该工具提供了开箱即用的路由机制,通常在微服务应用程序中使用,作为一种将多个服务隐藏在单一门面后面的方式。

For an explanation of the Gateway pattern without the Spring Cloud Gateway project, check out our previous article.

有关不含 Spring Cloud Gateway 项目的 Gateway 模式的解释,请查看我们的上一篇文章

2. Routing Handler

2.路由处理程序

Being focused on routing requests, the Spring Cloud Gateway forwards requests to a Gateway Handler Mapping, which determines what should be done with requests matching a specific route.

由于专注于路由请求,Spring Cloud Gateway将请求转发到Gateway Handler Mapping,该Mapping决定对匹配特定路由的请求应该做什么。

Let’s start with a quick example of how the Gateway Handler resolves route configurations by using RouteLocator:

让我们从一个快速的例子开始,看看网关处理程序如何通过使用RouteLocator来解析路由配置。

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
      .route("r1", r -> r.host("**.baeldung.com")
        .and()
        .path("/baeldung")
        .uri("http://baeldung.com"))
      .route(r -> r.host("**.baeldung.com")
        .and()
        .path("/myOtherRouting")
        .filters(f -> f.prefixPath("/myPrefix"))
        .uri("http://othersite.com")
        .id("myOtherID"))
    .build();
}

Notice how we made use of the main building blocks of this API:

请注意我们是如何利用这个API的主要构建模块的。

  • Route — the primary API of the gateway. It is defined by a given identification (ID), a destination (URI) and set of predicates and filters.
  • Predicate — a Java 8 Predicate — which is used for matching HTTP requests using headers, methods or parameters
  • Filter — a standard Spring WebFilter

3. Dynamic Routing

3.动态路由

Just like Zuul, Spring Cloud Gateway provides means for routing requests to different services.

正如Zuul一样,Spring Cloud Gateway提供了将请求路由到不同服务的手段。

The routing configuration can be created by using pure Java (RouteLocator, as shown in the example in Section 2) or by using properties configuration:

路由配置可以通过使用纯Java(RouteLocator,如第2节中的例子所示)或使用属性配置来创建。

spring:
  application:
    name: gateway-service  
  cloud:
    gateway:
      routes:
      - id: baeldung
        uri: baeldung.com
      - id: myOtherRouting
        uri: localhost:9999

4. Routing Factories

4.路由工厂

Spring Cloud Gateway matches routes using the Spring WebFlux HandlerMapping infrastructure.

Spring Cloud Gateway使用Spring WebFlux HandlerMapping基础设施来匹配路由。

It also includes many built-in Route Predicate Factories. All these predicates match different attributes of the HTTP request. Multiple Route Predicate Factories can be combined via the logical “and”.

它还包括许多内置的路由谓词工厂。所有这些谓词都与HTTP请求的不同属性相匹配。多个路由谓词因子可以通过逻辑 “和 “来组合。

Route matching can be applied both programmatically and via configuration properties file using a different type of Route Predicate Factories.

路线匹配可以通过编程方式应用,也可以通过配置属性文件使用不同类型的路线谓词因子。

Our article Spring Cloud Gateway Routing Predicate Factories explores routing factories in more detail.

我们的文章Spring Cloud Gateway Routing Predicate Factories更详细地探讨了路由工厂。

5. WebFilter Factories

5.网络过滤器工厂

Route filters make the modification of the incoming HTTP request or outgoing HTTP response possible.

路线过滤器使修改传入的HTTP请求或传出的HTTP响应成为可能。

Spring Cloud Gateway includes many built-in WebFilter Factories as well as the possibility to create custom filters.

Spring Cloud Gateway包括许多内置的WebFilter Factories,以及创建自定义过滤器的可能性。

Our article Spring Cloud Gateway WebFilter Factories explores WebFilter factories in more detail.

我们的文章Spring Cloud Gateway WebFilter Factories更详细地探讨了WebFilter工厂。

6. Spring Cloud DiscoveryClient Support

6.Spring Cloud DiscoveryClient支持

Spring Cloud Gateway can be easily integrated with Service Discovery and Registry libraries, such as Eureka Server and Consul:

Spring Cloud Gateway可以很容易地与服务发现和注册库集成,如Eureka Server和Consul。

@Configuration
@EnableDiscoveryClient
public class GatewayDiscoveryConfiguration {
 
    @Bean
    public DiscoveryClientRouteDefinitionLocator 
      discoveryClientRouteLocator(DiscoveryClient discoveryClient) {
 
        return new DiscoveryClientRouteDefinitionLocator(discoveryClient);
    }
}

6.1. LoadBalancerClient Filter

6.1.LoadBalancerClient 过滤器

The LoadBalancerClientFilter looks for a URI in the exchange attribute property using ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR.

LoadBalancerClientFilter使用ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR在交换属性属性中寻找一个URI。

If the URL has a lb scheme (e.g., lb://baeldung-service), it’ll use the Spring Cloud LoadBalancerClient to resolve the name (i.e., baeldung-service) to an actual host and port.

如果URL有lb方案(例如,lb://baeldung-service),它将使用Spring Cloud LoadBalancerClient来将名称(即,baeldung-service)解析为实际的主机和端口。

The unmodified original URL is placed in the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR attribute.

未经修改的原始URL被放在ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR属性中。

7. Monitoring

7.监测

Spring Cloud Gateway makes use of the Actuator API, a well-known Spring Boot library that provides several out-of-the-box services for monitoring the application.

Spring Cloud Gateway利用了Actuator API,这是一个著名的Spring Boot库,为监控应用程序提供了几个开箱即用的服务。

Once the Actuator API is installed and configured, the gateway monitoring features can be visualized by accessing /gateway/ endpoint.

一旦Actuator API被安装和配置,就可以通过访问/gateway/端点来实现网关监控功能的可视化。

8. Implementation

8.实施

We’ll now create a simple example of the usage of Spring Cloud Gateway as a proxy server using the path predicate.

现在我们将使用path predicate创建一个使用Spring Cloud Gateway作为代理服务器的简单例子。

8.1. Dependencies

8.1.依赖关系

The Spring Cloud Gateway is currently in the milestones repository, on version 2.0.0.RC2. This is also the version we’re using here.

Spring Cloud Gateway目前在里程碑仓库中,版本为2.0.0.RC2。这也是我们在这里使用的版本。

To add the project, we’ll use the dependency management system:

为了添加项目,我们将使用依赖性管理系统。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gateway</artifactId>
            <version>2.0.0.RC2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Next, we’ll add the necessary dependencies:

接下来,我们将添加必要的依赖性。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

8.2. Code Implementation

8.2.代码实施

And now we create a simple routing configuration in the application.yml file:

而现在我们在application.yml文件中创建一个简单的路由配置。

spring:
  cloud:
    gateway:
      routes:
      - id: baeldung_route
        uri: http://baeldung.com
        predicates:
        - Path=/baeldung/
management:
  endpoints:
    web:
      exposure:
        include: "*'

And here’s the Gateway application code:

这里是Gateway的应用代码。

@SpringBootApplication
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

After the application starts, we can access the url “http://localhost/actuator/gateway/routes/baeldung_route” to check all routing configuration created:

应用程序启动后,我们可以访问网址 “http://localhost/actuator/gateway/routes/baeldung_route”,以检查所有创建的路由配置。

{
    "id":"baeldung_route",
    "predicates":[{
        "name":"Path",
        "args":{"_genkey_0":"/baeldung"}
    }],
    "filters":[],
    "uri":"http://baeldung.com",
    "order":0
}

We see that the relative url “/baeldung” is configured as a route. So, hitting the url “http://localhost/baeldung”, we’ll be redirected to “http://baeldung.com”, as was configured in our example.

我们看到相对网址“/baeldung”被配置为一个路由。因此,点击网址“http://localhost/baeldung”,我们将被重定向到“http://baeldung.com”,正如我们的例子中所配置的那样。

9. Conclusion

9.结论

In this article, we explored some of the features and components that are part of Spring Cloud Gateway. This new API provides out-of-the-box tools for gateway and proxy support.

在这篇文章中,我们探讨了作为Spring Cloud Gateway一部分的一些功能和组件。这个新的API为网关和代理支持提供了开箱即用的工具。

The examples presented here can be found in our GitHub repository.

这里介绍的例子可以在我们的GitHub 仓库中找到。