1. The background

Spring-cloud-gateway is a gateway implementation that replaces Zuul, and we’ll look at it in this section.

2. Knowledge

Spring-cloud-gateway provides an API gateway built on top of the Spring ecosystem, designed to provide a simple and efficient way to route apis and provide them with crosscutting concerns such as security, monitoring/metrics, and resiliency.

Features:

  • Dynamic routing
  • Route matching supports handler mapping built into Spring
  • Route matching of HTTP requests (path, method, header, host, etc.)
  • Filters that support matching routes

Filters are an important component that can modify downstream HTTP requests and HTTP responses (add/remove headers, add/remove parameters, overwrite paths, set paths, Hystrix, etc…).

Example 3.

1. Add dependencies

dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-gateway' testImplementation 'org.springframework.boot:spring-boot-starter-test' implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' implementation 'org.springframework.boot:spring-boot-starter-actuator' compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.20' implementation Group: 'com.google.code.gson', name: 'gson', version: '2.8.6'}Copy the code

The configuration file

server: port: 9000 spring: application: name: api-gateway cloud: gateway: discovery: locator: enabled: true lower-case-service-id: true globalcors: corsConfigurations: '[/auth/**]': allowedOrigins: '*' allowedHeaders: - x-auth-token - x-request-id - Content-Type - x-requested-with - x-request-id allowedMethods: - GET - POST - OPTIONS routes: - id: auth-service uri: lb://auth-service predicates: - Path=/auth/** filters: - StripPrefix=1 - id: hello-service-1 uri: lb://hello-service-1 predicates: - Path=/hello/** filters: - StripPrefix=1 eureka: client: serviceUrl: defaultZone: http://localhost:1111/eureka/ instance: prefer-ip-address: True # Gateway log level, the output forwarded details logging: level: org. Springframework. Cloud. Gateway: the debugCopy the code

Note The Eureka client is configured, registers itself with Eureka, and obtains the service list from Eureka.

Route configuration has this configuration in the Router section

id: auth-service
          uri: lb://auth-service
          predicates:
            - Path=/auth/**
          filters:
            - StripPrefix=1
Copy the code

It describes the address from /auth/**, routed to the lb://auth-service service. Here I combine the use of Eureka and will send requests to the service instance registered in Eureka named “auth-service”.

StripPrefix=1 indicates that the address should be forwarded to a specific instance service after the first path node is processed during routing.

filters:
            - StripPrefix=1
Copy the code

4. The extension

My Demo example: github.com/vir56k/demo…

5. Reference:

Spring. IO /projects/sp… Github.com/spring-clou… Spring. IO/guides/gs/g…