6.【Spring Cloud Alibaba】API網關-SpringCloudGateway


SpringCloud Gateway是什么?優缺點分析

image

springCloud Gateway優點

image

springCloud Gateway缺點

image

編寫SpringCloundGateway

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

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
application.yml
server:
  port: 8040
spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      discovery:
        locator:
          # 讓gateway通過服務發現組件找到其他的微服務
          enabled: true
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always
logging:
  level:
    org.springframework.cloud.gateway: trace

image

核心概念

image

路由配置示例

image

架構剖析

image

路由謂詞工廠詳解

路由謂詞工廠的作用是:符合Predicate的條件,就使用該路由的配置,否則就不管

路由謂詞工廠詳解

image

自定義路由謂詞工廠

TimeBetweenRoutePredicateFactory
@Component
public class TimeBetweenRoutePredicateFactory
    extends AbstractRoutePredicateFactory<TimeBeweenConfig> {
    public TimeBetweenRoutePredicateFactory() {
        super(TimeBeweenConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(TimeBeweenConfig config) {
        LocalTime start = config.getStart();
        LocalTime end = config.getEnd();
        return exchange -> {
            LocalTime now = LocalTime.now();
            return now.isAfter(start) && now.isBefore(end);
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("start", "end");
    }

    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        System.out.println(formatter.format(LocalTime.now()));
    }
}
TimeBeweenConfig
@Data
public class TimeBeweenConfig {
    private LocalTime start;
    private LocalTime end;
}
application.yml

image

內置過濾器工廠詳解

過濾器工廠詳解

示例

image

自定義過濾器工廠

過濾器生命周期

image

自定義過濾器工廠方式01

image

image

自定義過濾器工廠方式02

image

image

自定義過濾器工廠核心API

image

編寫代碼 PreLogGatewayFilterFactory
@Slf4j
@Component
public class PreLogGatewayFilterFactory
    extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return ((exchange, chain) -> {
            log.info("請求進來了...{},{}", config.getName(), config.getValue());
            ServerHttpRequest modifiedRequest = exchange.getRequest()
                .mutate()
                .build();
            ServerWebExchange modifiedExchange = exchange.mutate()
                .request(modifiedRequest)
                .build();

            return chain.filter(modifiedExchange);
        });
    }
}

全局過濾器

Spring Cloud Gateway-全局過濾器

示例代碼
@Bean
@Order(-1)
public GlobalFilter a() {
    return (exchange, chain) -> {
        log.info("first pre filter");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("third post filter");
        }));
    };
}

@Bean
@Order(0)
public GlobalFilter b() {
    return (exchange, chain) -> {
        log.info("second pre filter");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("second post filter");
        }));
    };
}

@Bean
@Order(1)
public GlobalFilter c() {
    return (exchange, chain) -> {
        log.info("third pre filter");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("first post filter");
        }));
    };
}

監控Spring Cloud Gateway

Spring Cloud Gateway監控

image

排錯,調試技巧總結

Spring Cloud Gateway排錯、調試技巧總結

第一式:Actuator監控端點
    借助Actuator的監控端點,可分析全局過濾器、過濾器工廠、路由詳情。詳見:Spring Cloud Gateway監控

第二式:日志
    加日志,按需將如下包的日志級別設置成 debug 或 trace ,總有一款對你有用。
    
    org.springframework.cloud.gateway
    org.springframework.http.server.reactive
    org.springframework.web.reactive
    org.springframework.boot.autoconfigure.web
    reactor.netty
    redisratelimiter
    配置示例:
    
    logging:
      level:
        org.springframework.cloud.gateway: trace
        
第三式:Wiretap【從Greenwich SR3及更高版本才會支持】
    Reactor Netty HttpClient 以及 HttpServer 可啟用 Wiretap 。將reactor.netty 包設置成 debug 或 trace ,然后設置如下屬性:
    
    spring.cloud.gateway.httpserver.wiretap=true
    spring.cloud.gateway.httpclient.wiretap=true
    分別開啟HttpServer及HttpClient的Wiretap。
    
    然后,就可以分析日志啦。

過濾器的執行順序

image

image

image

image

image

SpringCloudGateway限流

Spring Cloud Gateway限流詳解

本章總結

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM