Spring Cloud Gateway Setup Guide

The configuration of Spring Cloud Gateway component can be done either through configuration files or through coding.

The following properties can be used for configuration in the configuration file:

  1. server.port specifies the port number of the Gateway.
  2. spring.application.name: Specifies the application name of the Gateway.
  3. ID: The ID of the router can be arbitrarily specified.
  4. uri: The URL of the target service.
  5. Predicates are the matching criteria for routing, which can be based on the request’s path, method, headers, and more.
  6. Filters are used in routing to pre-process, post-process, and handle requests.

For example, here is a simple configuration file example.

server:
  port: 8080

spring:
  application:
    name: gateway

spring:
  cloud:
    gateway:
      routes:
        - id: route1
          uri: http://localhost:8001
          predicates:
            - Path=/api/**
        - id: route2
          uri: http://localhost:8002
          predicates:
            - Path=/hello/**
          filters:
            - AddRequestHeader=X-Request-Id, 12345

The above configuration specifies that requests matching the /api/** path will be forwarded to http://localhost:8001, requests matching the /hello/** path will be forwarded to http://localhost:8002, and a header named X-Request-Id with a value of 12345 will be added when forwarding the requests.

If you need to configure using a coding method, you can create an instance of RouteLocator using the @Bean annotation and configure it through its API.

For example:

@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("route1", r -> r.path("/api/**")
                .uri("http://localhost:8001"))
            .route("route2", r -> r.path("/hello/**")
                .filters(f -> f.addRequestHeader("X-Request-Id", "12345"))
                .uri("http://localhost:8002"))
            .build();
    }

}

The code above sets up a route rule called myRoutes that forwards requests matching /api/** paths to http://localhost:8001, requests matching /hello/** paths to http://localhost:8002, and includes a header named X-Request-Id with a value of 12345 when forwarding the requests.

bannerAds