当前位置:网站首页>Gateway new generation gateway

Gateway new generation gateway

2022-07-19 08:27:00 Illusory clarity

1. Introduce

Cloud One of the most important components in the family bucket is the gateway , stay 1 .x It's used in all versions Zuu| gateway ;

But in 2.x In the version ,zuul Upgrade one Skip ticket , SpringCloud Finally, I developed it myself A gateway replacement Zuul, That's it SpringCloud Gateway- Sentence : gateway Is the original zuul1.x Replacement of version .
 Insert picture description here

Gateway Is in Spring Built on the ecosystem API Gateway service , be based on Spring 5, Spring Boot 2 and Project Reactor Technology .

Gateway Designed to provide a simple And an effective way to API Routing , And provide some powerful filter functions , for example : Fuse 、 Current limiting 、 Retry etc. .

SpringCloud Gateway yes Spring Cloud A brand new project , be based on Spring 5.0+ Spring Boot 2.0 and Project Reactor Such as technology development gateway , It aims to provide a simple and effective unified approach to microservice architecture API Routing management .

SpringCloud Gateway As Spring Cloud Gateways in an ecosystem , The goal is to replace Zuul, stay Spring Cloud 2.0 In the above version , There is no new version of Zuul 2.0 The latest performance version above is integrated , Still used Zuul 1.x Not Reactor The old version of the pattern . In order to improve the performance of the gateway ,I SpringCloud Gateway Is based on WebFlux Framework implementation , and WebFlux The bottom layer of the framework uses high-performance Reactor Mode communication framework Netty.

Spring Cloud Gateway Our goal is to provide - Routing Party of Formula and based on Filter The chain approach provides the gateway's basic functionality , for example : Security , monitor / indicators , And current limiting .

Gateway Official website

What can I do? ?
 Insert picture description here

Where is the gateway in the microservice architecture ?

 Insert picture description here

With Zuul Why did you come out again gateway?

Why do we choose Gatway?
1.neflix Not very reliable ,zuul2.0 Keep skipping tickets , Delayed release
 Insert picture description here

2.SpringCloud Gateway Has the following characteristics
 Insert picture description here

3.SpringCloud Gateway And Zuul The difference between
 Insert picture description here
GateWay Model
 Insert picture description here

Three core concepts

1.Route( route )
Routing is the basic module of building a gateway , It consists of ID, The goal is URI, A series of assertions and filters , If the assertion is true Then match the route .

2.Predicate( Assertion )
The reference is java8 Of java.util.function.Predicate Developers can match HTTP Everything in the request ( For example, request header or request parameter ), If the request matches the assertion, route it .

3.Filter( Filter )
refer to Spring In the frame GatewayFilter Example , Use filters , Requests can be modified before or after they are routed .

 Insert picture description here

Gateway Workflow

The official website summarizes
 Insert picture description here
 Insert picture description here
Core logic :
Routing and forwarding + Execute the filter chain

Entry configuration

newly build Module
1. New module cloud-gateway-gateway9527
2. modify POM.xml

<dependencies>
        <!--   gateway     -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--   web Gateway Unwanted web rely on      -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>com.zhang.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

3. establish application.yml file

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
#      discovery:
#        locator:
#          enabled: true  # Enable the registry routing function 
      #          lower-case-service-id: true
      routes:
        - id: payment_routh
          uri: http://localhost:8001
          #uri: lb://cloud-payment-service # If there is a problem here , Please pay attention to dependency spring-cloud-starter-netflix-eureka-client Dependence cannot be wrong 
          predicates:
            - Path=/payment/get/**
        - id: payment_routh2
          uri: http://localhost:8001
          #uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/lb/**
eureka:
  instance:
    hostname: cloud-gateway-service
  client:      # Service providers provider Sign up for eureka In the list of services 
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://eureka7001.com:7001/eureka #,http://eureka7002.com:7002/eureka
#logging:
#  level:
#    root: debug

4. Main startup class

@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GateWayMain9527.class,args);
    }
}
  1. 9527 How does the gateway do routing mapping ?
     Insert picture description here

Gateway Gateway routing can be configured in two ways

1. In profile yml Middle configuration

2. Inject... Into the code RouteLocator Of Bean
establish config class

public class GateWayConfig {

    /**
     *  Route builder 
     * @param routeLocatorBuilder
     * @return
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){

        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
        routes.route("path_route_zhang"
                        , r->r.path("/guonei").uri("http://news.baidu.com/guonei"))
                .build();
        return routes.build();
    }
}

Dynamic routing through microservice name

By default Gateway According to the service list of the registry , Create a dynamic route with the micro service name on the registry as the path to forward , So as to realize the function of dynamic routing .

It should be noted that uri The agreement is lb, Means to enable Gateway Load balancing function of .

modify application.yml

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  # Enable the registry routing function 
      #          lower-case-service-id: true
      routes:
        - id: payment_routh
          #uri: http://localhost:8001
          uri: lb://cloud-payment-service # If there is a problem here , Please pay attention to dependency spring-cloud-starter-netflix-eureka-client Dependence cannot be wrong 
          predicates:
            - Path=/payment/get/**
        - id: payment_routh2
          #uri: http://localhost:8001
          uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/lb/**
eureka:
  instance:
    hostname: cloud-gateway-service
  client:      # Service providers provider Sign up for eureka In the list of services 
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://eureka7001.com:7001/eureka #,http://eureka7002.com:7002/eureka

lb://serviceName yes spring cloud gateway Load balancing created for us automatically in microservices uri.

Filter Use

1. What is it?
Routing filters can be used to modify incoming HTTP Requested and returned HTTP Respond to ; Routing filters can only specify routes to use .

Spring Cloud GateWay Built in many routing filters , They are all made up of GateWayFilter Factory class .

 Insert picture description here

Custom filter

1. What can I do?
Global logging . Unified gateway authentication …

2. Custom global GlobalFilter

package com.zhang.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter,Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("**************** come in MyLogGateWayFilter:  " + new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null){
            log.info("************ The user is called null, For illegal users ,!!!!!!!!");
            exchange.getResponse().setStatusCode(HttpStatus.NO_CONTENT);
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
原网站

版权声明
本文为[Illusory clarity]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207170723511777.html