define

The unified service entrance of the gateway facilitates the management and control of various service interfaces on the platform, authentication of access services, anti-packet replay and anti-data tampering, service authentication of function invocation, desensitization of response data, traffic and concurrency control, and even metering or charging based on API invocation.

role

  • Routing and forwarding: Receives all external requests and forwards them to the backend microservice.
  • Filters: A number of crosscutting functions can be performed in a service gateway, such as permission verification, traffic limiting, and monitoring.

Why do you need a gateway?

  1. The gateway implements unified service management.
  2. Gateways can solve the redundancy problems of common code in microservices (such as permission control, traffic monitoring, traffic limiting, etc.).

Gateway architecture in microservices

The Gateway component

1.

This project provides a library to build API gateways on top of Spring MVC. The Spring Cloud Gateway aims to provide a simple and efficient way to route apis and provide crosscutting concerns for apis. For example: security, monitoring/measurement, and resilience.

2. The characteristics of

  • Based on the Spring Boot2.x, Spring WebFlux and Reactor construction
  • Reactive asynchronous non-blocking IO model
  • Dynamic routing
  • The request filtering

Gateway dynamic route development

In Gateway, you can configure dynamic routing using configuration files or configuration classes. Since Spring Cloud officially recommends using configuration files to configure dynamic routing, this article does not cover using configuration classes to configure dynamic routing.

1. Configure the gateway for directional access

  1. Create a separate Gateway module.

  2. Register the module into a service registry (in this article, Consul is the registry).

  3. Modules introduce dependencies

    <dependency>
        <groupId>org.springframework.cloud</groupId>   
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    Copy the code
  4. Module writes gateway configuration

    spring:
      application:
        name: gateway
      cloud:
        # consul configuration
        consul:
          .
        # gateway configuration
        gateway:
          routes:
            # Unique identifier of the route
            - id: product_route
              # Route access address
              uri: http://localhost:9001/
              # Route matching rule
              predicates:
                - Path=/product/**
            - id: user_route
              uri: http://localhost:9002/
              predicates:
                - Path=/user/**
    Copy the code
  5. If you access http://gateway IP: gateway port/Path, the gateway automatically switches to the URI /Path based on the configuration file to access interfaces of different services.

Note:

  1. When the spring-cloud-starter-gateway dependency is introduced along with the spring-boot-starter-web dependency, the project fails to start. Gateway is developed based on Spring WebFlux, which encapsulates Spring MVC. If both dependencies are introduced at the same time, conflicts can result. Therefore, you must remove the spring-boot-starter-Web dependency when using the Gateway component.

  2. The Gateway service does not import the Common service. Because the Spring-boot-starter-web dependency is configured in the common service, you need to manually configure Consul.

  3. In configuring routes

    predicates:
      - Path=/product/**
    Copy the code

    This configuration is a collection (string data) configuration in YML files, and the prototype is

    predicates: [Path=/product/**]
    Copy the code

    The ** here represents multi-level path matching.

  4. In configuring routes

    routes:
      - id: product_route
        uri: http://localhost:9001/
        predicates:
          - Path=/product/**
      - id: user_route
        uri: http://localhost:9002/
        predicates:
          - Path=/user/**
    Copy the code

    This configuration is set (object data) configuration in YML files, prototype is

    routes:[{id: product_route.uri: http://localhost:9001/.predicates: [Path=/product/**] {},id: user_route.uri: http://localhost:9002/.predicates: [Path=/user/**]}]Copy the code

2. Configure gateway load balancing

  1. Create the Gateway module, register, and import dependencies.

  2. The gateway configuration

    spring:
      application:
        name: gateway
      cloud:
        # consul configuration
        consul:
          host: localhost
          port: 8500
          discovery:
            service-name: ${spring.application.name}
        # gateway configuration
        gateway:
          routes:
            - id: product_route
              uri: lb://products
              predicates:
                - Path=/product/**
            - id: user_route
              uri: lb://users
              predicates:
                - Path=/user/**
          discovery:
            Enable dynamic routing by service name
            locator:
              enabled: true
    Copy the code

Note:

  1. In configuring the gateway

    uri: lb://products
    Copy the code

    Lb: the gateway uses a load balancing policy to access services.

    Products: indicates the specific service name of the registry.

Resolve Gateway cross-domain issues

In a project where the front and back ends are separated, if nginx was originally used as a reverse proxy and load balancer, simply disabling Nginx and configuring the Gateway as described above can cause cross-domain problems.

Because the Gateway uses WebFlux instead of SpringMVC, the @Crossorigin backend configuration does not solve the cross-domain problem. You need to disable the WebFlux CORS and then configure the CORS in the Gateway filter.

  1. Change the nginx address to the gateway address on the front end

  2. Remove @crossorigin annotations from all controllers at the back end

  3. Configure application.yml in the Gateway service

    spring:
      application:
        name: afterlives-gateway
      cloud:
      	# consul configuration
        consul:
          .
        # gateway configuration
        gateway:
          routes:
           .
          discovery:
           .
          Configure cross-domain
          globalcors:
            corsConfigurations:
              '[/ * *]':
                allowedHeaders: "*"
                allowedOrigins: "*"
                allowedMethods:
                  - GET
                    POST
                    DELETE
                    PUT
                    OPTION
    Copy the code
  4. Create the Config package in the Gateway service and create the CorsConfig class

    / / gateway across domains
    @Configuration
    public class CorsConfig {
    
        @Bean
        public CorsWebFilter corsFilter(a) {
            CorsConfiguration config = new CorsConfiguration();
            config.addAllowedMethod("*");
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
    
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
            source.registerCorsConfiguration("/ * *", config);
    
            return newCorsWebFilter(source); }}Copy the code

View the gateway routing rule list

Gateway provides a Web interface for routing access rule lists, but is disabled by default. If you want to view service routing rules, you can enable it in the configuration file.

  1. The Gateway module opens all Web endpoints (including those exposed by the Gateway)

    management:
      endpoints:
        web:
          exposure:
            include: "*"
    Copy the code
  2. If the registry uses Nacos, you also need to add the following configuration to the Gateway

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    Copy the code
  3. Access to the list of routing management address: http:// gateway IP: gateway port/physical/gateway/routes