[service gateway] [getway] of spring cloud micro Service -- continuous update

Posted by maca134 on Fri, 11 Feb 2022 00:29:16 +0100

Why use a gateway?

All requests can be uniformly standardized and processed through the gateway side, and unified logging, permission verification, flow restriction, interface service security reinforcement, reverse proxy, etc. can also be done.

The function of this gateway is equivalent to that you go to the hospital to see a doctor. First, register at the triage desk, and then guide you to different departments to see a doctor. Instead of you going directly to a certain department to see a doctor, it's a mess. Therefore, the gateway must exist in the micro service architecture.

Developed by gateway spring community

reference resources

https://blog.csdn.net/qq_38380025/article/details/102968559

 

Understanding of microservice gateway

spring official website address: https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/

pom.xml Core dependency

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

SpringCloud Gateway

Architecture diagram (the gateway with red box is the general term of unified gateway)

In the microservice architecture, where does the gateway exist?

As can be seen from the architecture diagram, all micro services are not directly exposed, but are uniformly distributed and managed through the gateway.

Why spring cloud gateway

Spring cloud gateway feature

What is the difference between spring cloud gateway and zuul

zuul model (1.X)

webflux

springcloud gateway concept

  • Route route

  • predicate assertion

  • filter filtering

  • population

The above figure is the core flow chart. The most important is that routes, predictions and Filters act on specific routes.

1) Route: * * route is the basic component of gateway * *. It is defined by ID, target URI, predicate set and filter set. If the aggregation predicate is true, the route is matched.

2) Predict: * * refer to the new feature predict * * of Java 8. This allows developers to match anything in the HTTP request, such as headers or parameters.

3) Filter: requests and responses can be modified before or after sending downstream requests.

gateway workflow

The overall core and logic are actually: routing forwarding and filter chain execution. The purpose is to call the final micro service provider after processing through the gateway;

Demo setup -- gateway configuration

  • Configure POM XML dependency
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-gateway</artifactId>
        <groupId>com.wolf.boy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-cloud-gateway-spring</artifactId>
    <dependencies>
 
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--Additional introduction gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>

</project>

be careful:

There is no need to introduce spring boot starter web dependency. Otherwise, an error will be reported when starting, because it is not needed at all.

  • Configuring yml profiles

Basic configuration

server:
  port: 6666
spring:
  application:
    name: spring-cloud-gateway-spring
#Eureka service provider configuration
eureka:
  client:
    #false means you don't register yourself with the registry (you are a eureka service, so you don't have to register yourself)
    register-with-eureka: false
    #false means that my client is the registration center. My responsibility is to maintain service instances and I don't need to retrieve services
    #This is mainly used in conjunction with discoveryClient
    fetch-registry: true
    service-url:
      #Stand alone version
      defaultZone: http://localhost:9999/eureka

Add gateway configuration [routing mapping]

Mapping configuration

There are two gateway mapping configurations

(1) Based on yml, configuration file

server:
  port: 9438
spring:
  application:
    name: spring-cloud-gateway-spring
  cloud:
    gateway:
      routes:
        #The ID of the route has no fixed rules, but it is required to be unique. It is generally recommended to match the service name
        - id: provider_01_routh
          uri:  http://localhost:8881 # matches the routing address of the service (equivalent to prefix)
          predicates:
            - Path=/user/get/** #Assert that the route matches the route; That is, the address you requested is this. I'll use it when I match it
            #-The request will be transferred to the east area of google t1789-25:00 at 12:00:00-18 at 12:00:00 in 2018.
            #-After=2018-12-25T14:33:47.789+08:00 the routing rule will transfer all requests to google after 2018-12-25 14:33:47 in East Zone 8
            #- Between=2018-12-25T14:33:47.789+08:00, 2018-12-26T14:33:47.789+08:00
            #-Cookie = cookie, cookie value route matching request. If there is a cookie named cookie, and the cookie content matches cookie value, forward the request to google.
            #-Header=X-Request-Id, \d + route matches the request with a header named X-Request-Id and a number. Forward the request to google.
            #- Host=**.somehost.org,**.anotherhost.org route will match the host, such as www.somehost.org Org or beta somehost. Org or www.otherhost.com Org and other requests.
            #-Method=GET route will match all GET method requests.
            #-Path=/foo/{segment},/bar/{segment} the above route can match, such as: / foo/1 or / foo/bar or / bar/baz. The segment variable can be obtained in the following way
            #- Query=foo, ba.  The route will match all that contain foo, and the content of foo is ba compliant, such as bar or baz Regular rule request
            #-RemoteAddr=192.168.1.1/24. The above route will match RemoteAddr requests such as 192.168.1.10.
        - id: provider_02_routh
          uri: http://localhost:8881
          predicates:
            - Path=/user/gateway/** #Assert that the route matches the route; That is, the address you requested is this. I'll use it when I match it
#Eureka service provider configuration
eureka:
  client:
    #false means you don't register yourself with the registry (you are a eureka service, so you don't have to register yourself)
    register-with-eureka: false
    #false means that my client is the registration center. My responsibility is to maintain service instances and I don't need to retrieve services
    #This is mainly used in conjunction with discoveryClient
    fetch-registry: true
    service-url:
      #Stand alone version
      defaultZone: http://localhost:9999/eureka
      #Cluster version
      #defaultZone: http://eureka9999.server:9999/eureka,http://eureka9998.server:9998/eureka

(2) Code based

Official reference https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/

 

@Configuration
public class GateWayConfig {

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {
        //Get a routes object (same as yml)
        RouteLocatorBuilder.Builder routes = builder.routes();
        //PredicateSpec return:AsyncBuilder
        routes.route("provider_01_routh_java_config_02",ps->{
            return ps.path("/guonei").uri("https://news.baidu.com/guonei");
        }).build();
        return routes.build();
    }
}
  • Write business class
  • Main startup class configuration
@SpringBootApplication
//Open service provider (registered in Eureka)
@EnableEurekaClient
public class RunClientGateWayMain {
    public static void main(String[] args) {
        SpringApplication.run(RunClientMain.class,args);
    }
}
  • View results

Under normal circumstances, if you know the IP address + port of the service provider, you can also access it normally

http://localhost:8881/user/get

But now that there is a gateway, the request goes through the gateway first

http://localhost:9438/user/get

Configure dynamic routing (based on service name)

You need to prepare a service registry, and then two service providers;

A service name with 2 service instances below;

yml adjustment part

spring:
  cloud:
    gateway:
      #[add parameter]
      discovery:
        locator:
          enabled: true #Enable the function of dynamically creating routes from the service registry, and use microservices for routing
		  
Modified part
#http://localhost:8881 # matches the routing address of the service (equivalent to prefix)
uri: lb://SPRING-CLOUD-EUREKA-PROVIDER-SERVER-01

Complete yml configuration

server:
  port: 9438
spring:
  application:
    name: spring-cloud-gateway-spring
  cloud:
    gateway:
      #[add parameter]
      discovery:
        locator:
          enabled: true #Enable the function of dynamically creating routes from the service registry, and use microservices for routing
      routes:
        #The ID of the route has no fixed rules, but it is required to be unique. It is generally recommended to match the service name
        - id: provider_01_routh
          uri:  http://localhost:8881 # matches the routing address of the service (equivalent to prefix)
          predicates:
            - Path=/user/get/** #A route that matches a route; That is, the address you requested is this. I can match it
          #http://localhost:8881 # matches the routing address of the service (equivalent to prefix)
          //[lb] don't Scribble, the service name will follow
          uri: lb://SPRING-CLOUD-EUREKA-PROVIDER-SERVER-01
          predicates:
            - Path=/user/gateway/** #Assert that the route matches the route; That is, the address you requested is this. I'll use it when I match it
#Eureka service provider configuration
eureka:
  client:
    #false means you don't register yourself with the registry (you are a eureka service, so you don't have to register yourself)
    register-with-eureka: false
    #false means that my client is the registration center. My responsibility is to maintain service instances and I don't need to retrieve services
    #This is mainly used in conjunction with discoveryClient
    fetch-registry: true
    service-url:
      #Stand alone version
      defaultZone: http://localhost:9999/eureka
      #Cluster version
      #defaultZone: http://eureka9999.server:9999/eureka,http://eureka9998.server:9998/eureka

Access effect after startup:

{"code":0,"msg":null,"result": "get user information from service port: 8882! gateway"}
{"code":0,"msg":null,"result": "get user information from service port: 8881! gateway"}

You can see the service and switch between 8881 and 8882; [load balancing of client based on gateway service is realized]

Predicate assertion

That is to say, we start to talk about the Yml configuration

Date acquisition method:

ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println(zonedDateTime.toString());
//console output 
2021-05-10T15:06:23.308+08:00[Asia/Shanghai]

Support for these.

Where do you see the above configurations? Official website https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories

Source code view implementation class

Filter filter

Before and after the request,

There are two types: single and global;

single

https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories

Global

https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#global-filters

Custom filter

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Topics: spring-cloud