SpringCloud Quick Start - GateWay Service GateWay

Preface

What if we don't want all requests to have access to our services?

Thus, this component, Gateway Gateway, is the unified gateway to all our micro services

Its core functions are as follows:

  • Privilege control: Gateway as a micro-service entry, needs to verify whether the user is eligible for requests, and if not intercepts
  • Routing and Load Balancing: All requests must go through the gateway first, but instead of handling business, the gateway forwards requests to a microservice according to certain rules, a process called routing. Of course, when there are multiple routing target services, load balancing is also required
  • Limit flow: When the request flow is too high, release the request in the gateway at a speed acceptable to downstream microservices to avoid excessive service pressure

In SpringCloud, there are two implementations of gateways:

  • gateway
  • zuul

Zuul is a Servlet-based implementation and belongs to blocking programming. SpringCloudGateway, which is based on WebFlux provided in Spring5, is an implementation of responsive programming with better performance

1. Gateway Quick Start

1. Create Gateway services and introduce dependencies

<!--gateway-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos Service Discovery Dependency-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2. Write startup classes

package cn.beizhen.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author : Bei-Zhen
 * @date : 2021-12-13 23:54
 */
@SpringBootApplication
public class GatewayApplication {

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

3. Write basic configuration and routing rules: create application.yml file

server:
  port: 10010 # Gateway Port
spring:
  application:
    name: gateway # Service Name
  cloud:
    nacos:
      server-addr: localhost:8848 # nacos address
    gateway:
      routes: # Gateway Routing Configuration
        - id: user-service # Route id, custom, unique only
          # uri: http://127.0. 0.1:8081 #Route's target address http is a fixed address
          uri: lb://The target address lb for userservice #routing is load balancing followed by the service name
          predicates: # Routing assertions, which determine whether a request meets the conditions of a routing rule
            - Path=/user/** # This matches by path, as long as it starts with/user/

4. Restart Test: Restart Gateway, Access http://localhost:10010/user/1 When the/user/** rule is met, the request is forwarded to the uri: http://userservice/user/1

5. Flow chart for gateway routing

2. Assertion factory

1. Gateway routes can be configured to include

  • Route id: Route unique identifier
  • uri: routing destination, supporting lb and http
  • predicates: A routing assertion that determines if a request meets the requirements and forwards it to a routing destination
  • Filters: Route filters, process requests or responses

2. The assertion rules we write in the configuration file are just strings, which are read and processed by Predicate Factory and turned into conditions for routing decisions

For example, Path=/user/** matches by path, which is determined by org. Springframework. Cloud. Gateway. Handler. Predicate. Processed by the PathRoutePredicateFactory class, there are more than a dozen assertion factories like this in SpringCloudGateway

3. Filter factories

GatewayFilter is a filter provided in a gateway that handles requests to enter the gateway and responses returned by microservices

1. Types of routing filters: Spring provides 31 different routing filter factories

2. Request Header Filter

Requirements: for all entries userservice Add a request header to your request: Truth=beizhen 666

Modify the application for the gateway service. YML file, add route filter

spring:
  cloud:
    gateway:
      routes:
      - id: user-service 
        uri: lb://userservice 
        predicates: 
        - Path=/user/** 
        filters: # Filter
        - AddRequestHeader=Truth=beizhen 666 # Add Request Header

3. If you want all routes to work, you can write the filter factory to default

spring:
  cloud:
    gateway:
      routes:
      - id: user-service 
        uri: lb://userservice 
        predicates: 
        - Path=/user/**
      default-filters: # Default Filter Items
      - AddRequestHeader=Truth, beizhen 666

4. Global filters

A global filter acts as a gateway handler for all requests and microservice responses, just as a GatewayFilter does. The difference is that GatewayFilter is defined by configuration and the processing logic is fixed; GlobalFilter's logic needs to be implemented by writing your own code

Defined by implementing the GlobalFilter interface

public interface GlobalFilter {
    /**
     *  Processing the current request, pass it to the next filter if necessary through {@link GatewayFilterChain}
     *
     * @param exchange Request context, where you can get information such as Request, Response, and so on
     * @param chain Used to delegate requests to the next filter 
     * @return {@code Mono<Void>} Returns the end of the current filter business
     */
    Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
}

5. Customize Global Filters

Requirements: Define a global filter, intercept requests, and determine if the parameters of the request satisfy the following conditions:

  • Is there authorization in the parameter,

  • Is the authorization parameter value beizhen

Release if both are satisfied, otherwise intercept

Implementation: Define a filter in the gateway, add the @Order annotation

package cn.itcast.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * validate logon
 *
 * @author : Bei-Zhen
 * @date : 2021-12-14 0:22
 */
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. Get Request Parameters
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        // 2. Get authorization
        String auth = params.getFirst("authorization");
        // 3. Efficacy
        if("beizhen".equals(auth)){
            //Release
            return  chain.filter(exchange);
        }
        // 4. Interception
        // 4.1. No access, set status code
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2 End processing
        return exchange.getResponse().setComplete();
    }
}

6. The effect is as follows

After adding authorization=beizhen


7. Order of filter execution

Requests to enter a gateway encounter three types of filters: the current route's filter, DefaultFilter, and GlobalFilter. After routing is requested, the current routing filter, DefaultFilter, GlobalFilter are merged into a filter chain (set), and each filter is executed in turn after sorting.

  • Each filter must specify an order value of type int. The smaller the order value, the higher the priority, and the higher the execution order
  • GlobalFilter specifies the order value by implementing the Ordered interface or by adding the @Order annotation, which we specify ourselves
  • The order of the route filter and defaultFilter is specified by Spring and increases from 1 in declarative order by default
  • When the order value of the filter is the same, it is executed in the order defaultFilter > Routing Filter > GlobalFilter

Principle:
Org. Springframework. Cloud. Gateway. Route. The RouteDefinitionRouteLocator#getFilters() method is to load defaultFilters first, then filters for a route, then merge

Org. Springframework. Cloud. Gateway. Handler. The FilteringWebHandler#handle() method loads a global filter, merges it with the previous filter and organizes the filter chain in order

IV. Cross-domain Issues

1. What is a cross-domain problem: Domain name inconsistency is cross-domain, mainly including

  • Domain names are different: www.taobao.com and www.taobao.org and www.jd.com and miaosha.jd.com

  • Domain names are the same, ports are different: localhost:8080 and localhost 8081

Cross-domain issue: Browser prohibits cross-domain ajax requests from originator and server, requests are blocked by browser

Solution: CORS, both front-end and back-end implementations, recommended back-end implementations

2. Solution: Gateway handles cross-domain CORS scenarios as well and can be implemented with simple configuration

spring:
  cloud:
    gateway:
      # . . . 
      globalcors: # Global cross-domain processing
        add-to-simple-url-handler-mapping: true # Resolve options request intercept issue
        corsConfigurations:
          '[/**]':
            allowedOrigins: # Which websites are allowed to request across domains 
              - "http://localhost:8090"
            allowedMethods: # Allowed cross-domain ajax requests
              - "GET"
              - "POST"
              - "DELETE"
              - "PUT"
              - "OPTIONS"
            allowedHeaders: "*" # Header information allowed in requests
            allowCredentials: true # Is cookie s allowed
            maxAge: 360000 # Validity period of this cross-domain detection

V. Summary

1. Role of gateways

  • Authentication and privilege verification of user requests
  • Routing user requests to microservices and load balancing
  • Limit flow to user requests

2. Gateway Setup Steps

  • Create projects to introduce nacos service discovery and gateway dependencies
  • Configure application.yml, including basic service information, nacos address, routing

3. Routing configuration includes

  • Route id: Unique identifier of the route
  • Route destination (uri): the destination address of the route, http for fixed address, lb for load balancing based on service name
  • Routing assertions: Rules for determining routes
  • Routing filters: Processing requests or responses

4. What is the role of PredicateFactory?

  • Read user-defined assertion conditions to make judgments about requests

5. What does Path=/user/** mean?

  • Path is considered to be compliant if it starts with/user

6. What is the function of the filter?

  • Processing requests or responses to routes, such as adding request headers
  • Filters configured under Route will only work on requests for the current route

7.What is the purpose of defaultFilters?

  • A filter that works for all routes

8. What does a global filter do?

  • Filters that work for all routes and can customize processing logic

9. Steps to implement a global filter?

  • Implement GlobalFilter interface
  • Add the @Order comment or implement the Ordered interface
  • Write processing logic

10. Execution order of routing filter, defaultFilter, global filter?

  • The lower the order value, the higher the priority
  • When the order value is the same, the order is defaultFilter first, then local route filter, and finally global filter

11.What are the parameters to configure across CORS domains?

  • Which domain names are allowed to cross domains
  • Which request headers are allowed
  • What types of requests are allowed
  • Is cookie allowed
  • How long is the validity period

Keywords: Spring Cloud Microservices gateway

Added by edawson003 on Mon, 13 Dec 2021 19:01:41 +0200