Bootstrap

项目中用的网关Gateway及SpringCloud

在现代微服务架构中,网关(Gateway)起到了至关重要的作用。它不仅负责路由请求,还提供了统一的认证、授权、负载均衡、限流等功能。Spring Cloud Gateway 是 Spring Cloud 生态系统中的一个重要组件,专门为微服务架构提供了一种简单而有效的 API 网关解决方案。本文将详细介绍 Spring Cloud Gateway 及其在项目中的应用。

一、Spring Cloud Gateway概述

1.1 Spring Cloud Gateway简介

Spring Cloud Gateway 是基于 Spring 5、Spring Boot 2 和 Project Reactor 的 API 网关。它旨在取代 Netflix Zuul,提供更高效和更强大的网关解决方案。其核心特点包括:

  • 反应式编程模型:基于 Project Reactor 的反应式编程,提供非阻塞的高性能处理。
  • 路由管理:支持各种灵活的路由匹配规则。
  • 过滤器:提供全局和局部过滤器机制,用于处理请求和响应。
  • 易于扩展:通过自定义过滤器和路由器,可以轻松扩展网关功能。

1.2 Spring Cloud Gateway的架构

Spring Cloud Gateway 的架构主要由三部分组成:

  • 路由(Routes) :定义请求路径与服务之间的映射关系。
  • 过滤器(Filters) :在请求处理过程中应用的一系列逻辑操作。
  • 断言(Predicates) :决定请求是否符合特定条件的布尔表达式。

二、Spring Cloud Gateway的配置

2.1 项目依赖

在 Spring Boot 项目中,引入 Spring Cloud Gateway 依赖:

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

2.2 配置路由

在 application.yml 文件中配置路由:

spring:
  cloud:
    gateway:
      routes:
        - id: service_route
          uri: http://localhost:8081
          predicates:
            - Path=/service/**
          filters:
            - StripPrefix=1
​

上述配置将 /service/** 的请求路由到 http://localhost:8081,并移除路径中的第一个前缀。

2.3 注册中心集成

通过集成 Eureka 注册中心,可以实现动态路由:

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
​

三、Spring Cloud Gateway的高级功能

3.1 过滤器

过滤器用于在请求进入和离开网关时进行处理。常见的过滤器包括:

  • Pre过滤器:在请求路由之前执行。
  • Post过滤器:在请求路由之后执行。

示例:自定义过滤器

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class CustomGlobalFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("Global Pre Filter executed");
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            System.out.println("Global Post Filter executed");
        }));
    }
}
​

3.2 熔断器

熔断器用于防止服务雪崩效应,通常与 Hystrix 或 Resilience4j 集成:

spring:
  cloud:
    gateway:
      routes:
        - id: service_route
          uri: lb://SERVICE-NAME
          filters:
            - name: CircuitBreaker
              args:
                name: myCircuitBreaker
                fallbackUri: forward:/fallback
​

3.3 限流

限流用于控制请求流量,防止服务过载:

spring:
  cloud:
    gateway:
      routes:
        - id: rate_limiter_route
          uri: http://localhost:8081
          predicates:
            - Path=/rate/**
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter:
                  replenishRate: 10
                  burstCapacity: 20
​

四、项目中的实际应用

在实际项目中,Spring Cloud Gateway 可以用来实现以下功能:

4.1 统一认证和授权

通过在网关层统一处理认证和授权逻辑,可以简化各个微服务的实现。通常在过滤器中实现认证逻辑,并在请求通过前验证用户身份。

4.2 动态路由和负载均衡

结合服务注册中心(如 Eureka),Spring Cloud Gateway 可以根据服务实例的变化动态更新路由表,并实现负载均衡。

4.3 日志记录和监控

在网关层实现全局日志记录和监控,可以方便地跟踪所有请求的处理情况,及时发现和解决问题。

;