The introduction

Hello, this is Anyin.

In # Spring Cloud Gateway and Spring WebFlux, we introduced how Spring Cloud Gateway interconnects with Spring WebFlux. Also found the Spring Cloud Gateway Filter workflow entry FilteringWebHandler#handle.

As we know, the Spring Cloud Gateway Filter distinguishes between two types: GlobalFilter and GatewayFilter. A GlobalFilter is a singleton and globally unique and applies to all routes. A GatewayFilter is not a singleton and is mounted to a specific route object during route loading.

Today, we’ll take a look at the Spring Cloud Gateway filter workflow

Filter merge

In the previous section, we learned that the Spring Cloud Gateway has two types of filters, so how does that apply to filters? Let’s look at the FilteringWebHandler#loadFilters method here.

private static List<GatewayFilter> loadFilters(List<GlobalFilter> filters) {
   return filters.stream().map(filter -> {
      GatewayFilterAdapter gatewayFilter = new GatewayFilterAdapter(filter);
      if (filter instanceof Ordered) {
         int order = ((Ordered) filter).getOrder();
         return new OrderedGatewayFilter(gatewayFilter, order);
      }
      return gatewayFilter;
   }).collect(Collectors.toList());
}
Copy the code

Here we can see that GlobalFilter is proxyed through the GatewayFilterAdapter class, wrapping it as a GatewayFilter. Here is an application of the proxy pattern: The GatewayFilterAdapter implements the GatewayFilter interface and holds a reference to GlobalFilter, successfully wrapping GlobalFilter as GatewayFilter through this proxy class.

Next, in the FilteringWebHandler#handle method, merge the GatewayFilter list and GlobalFilter list that are already mounted on the routing object.

public Mono<Void> handle(ServerWebExchange exchange) { Route route = exchange.getRequiredAttribute(GATEWAY_ROUTE_ATTR); List<GatewayFilter> gatewayFilters = route.getFilters(); List<GatewayFilter> combined = new ArrayList<>(this.globalfilters); // List<GatewayFilter> combined = new ArrayList<>(this.globalfilters); combined.addAll(gatewayFilters); AnnotationAwareOrderComparator.sort(combined); if (logger.isDebugEnabled()) { logger.debug("Sorted gatewayFilterFactories: " + combined); } / / through the chain of responsibility pattern to request the return of new DefaultGatewayFilterChain (combined) filter (exchange); }Copy the code

Filter specific work flow

In the last section, we can see all the filter objects into DefaultGatewayFilterChain classes, and then execute the filter method of the object. Then we look at DefaultGatewayFilterChain the internal implementation of the class.

DefaultGatewayFilterChain class is a chain of responsibility pattern choreographer, it holds two member variables:

  • List<GatewayFilter> filtersA list of all filters that need to be executed
  • int indexThe current filter index to execute

It has two constructors:

  • DefaultGatewayFilterChain(List<GatewayFilter> filters)The first time you initialize it, you have to set index to 0 and put it in the filter list
  • DefaultGatewayFilterChain(DefaultGatewayFilterChain parent, int index)Before each filter is executed, the index of the next filter and the information about the current filter are added to the next filter chain

In FilteringWebHandler. DefaultGatewayFilterChain# filter method, execute the filter chain, the code is as follows:

public Mono<Void> filter(ServerWebExchange exchange) {
        return Mono.defer(() -> {
                if (this.index < filters.size()) {
                        GatewayFilter filter = filters.get(this.index);
                        DefaultGatewayFilterChain chain = new DefaultGatewayFilterChain(this, this.index + 1);
                        return filter.filter(exchange, chain);
                }
                else {
                        return Mono.empty(); // complete
                }
        });
}
Copy the code

Before each filter filter method, will create a DefaultGatewayFilterChain object, and the next time you need to perform index of the filter and the filter list into the DefaultGatewayFilterChain, Exit the loop until the final filter list is complete.

The filter

There are some important filters in the Spring Cloud Gateway that we’ll take a look at here.

  • NettyRoutingFilter

Routing filter, put forward the concrete request to the downstream service, here is through reactor.net ty. The HTTP client. The HttpClient packet forwarding

  • ReactiveLoadBalancerClientFilter

Load balancing filter, this filter is mainly used to combine the registry, using lb:// proxy route, through the configured proxy route, resolve the specific service name, then combined with the spring-cloud-starter-loadbalancer component, according to the service name to find the corresponding instance. Client load balancing is performed, and the forwarding address of the specific instance is returned.

The following is an example of a Spring Cloud Gateway routing configuration with a registry:

gateway:
  routes:
    - id: anyin-center-base
      uri: lb://anyin-center-base
      predicates:
        - Path=/base/**
      filters:
        - StripPrefix=1
Copy the code
  • Uri: lb://anyin-center-base Specifies the proxy route information. The lb table name is a route that requires client load balancing, and its service name is anyin-center-base

  • Predicates :Path specifies the proxy Path, that is, accessing http://xxx/base to access the Base service

  • Filters. StripPrefix specifies the number of prefixes to ignore. In this case, it indicates that the base prefix is ignored, which is the root path from which the base service can be accessed

  • WebsocketRoutingFilter

Normal Gateway forwarding is HTTP protocol, but Spring Cloud Gateway can support Websocket protocol forwarding, through this filter.

The last

With three Spring Cloud Gateway source code analyses, you are confident that you have mastered the basics of Spring Cloud Gateway usage.

Put together links to the other two Spring Cloud Gateway articles

  • Implement Spring Cloud Gateway dynamic routing and built-in filters
  • The meeting point of Spring Cloud Gateway and Spring WebFlux

Above, if there is something wrong, welcome to discuss.

Add your personal wechat friends to discuss below: DaydayCoupons