spring-gateway配置的实现示例

 更新时间:2025年12月24日 08:25:16   作者:JavaBoy_XJ  
本文详细介绍了Spring Cloud Gateway的核心配置结构,分为全局配置和路由配置两大部分,下面就来详细的介绍一下spring-gateway配置的实现示例,感兴趣的可以了解一下

一、核心配置结构总览

spring:
  cloud:
    gateway:
      # 1. 全局配置
      default-filters: []
      globalcors: {}
      httpclient: {}
      metrics: {}
      
      # 2. 路由配置
      routes:
        - id: 
          uri: 
          predicates: []
          filters: []
          metadata: {}
          order: 0
          
      # 3. 发现服务配置
      discovery:
        locator:
          enabled: false
          
      # 4. 路由定义存储
      route:
        locator:
          cache:
            enabled: true

二、全局配置详解

全局过滤器

spring:
  cloud:
    gateway:
      default-filters:
        - AddRequestHeader=X-Request-Global, Global-Value
        - AddResponseHeader=X-Response-Global, Global-Value
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            key-resolver: "#{@ipKeyResolver}"

全局CORS配置

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowed-origins: "https://example.com"
            allowed-methods:
              - GET
              - POST
              - PUT
              - DELETE
              - OPTIONS
            allowed-headers:
              - Content-Type
              - Authorization
            exposed-headers:
              - X-Custom-Header
            allow-credentials: true
            max-age: 3600

HTTP客户端配置

spring:
  cloud:
    gateway:
      httpclient:
        # 连接池配置
        pool:
          type: ELASTIC          # 连接池类型: ELASTIC, FIXED
          max-connections: 1000  # 最大连接数
          acquire-timeout: 45000 # 获取连接超时(ms)
          
        # SSL配置
        ssl:
          use-insecure-trust-manager: false
          trusted-x509-certificates: []
          handshake-timeout: 10000
          close-notify-flush-timeout: 3000
          close-notify-read-timeout: 0
          
        # 代理配置
        proxy:
          host: proxy.example.com
          port: 8080
          username: user
          password: pass
          
        # 响应压缩
        compression: true

WebFlux配置

spring:
  cloud:
    gateway:
      # WebFlux配置
      httpclient:
        # 响应式客户端配置
        response-timeout: 60s
        connect-timeout: 30s
        max-header-size: 65536
        max-chunk-size: 65536
        max-initial-line-length: 4096
        
      # WebSocket支持
      websocket:
        max-frame-payload-length: 65536

uri配置详解

uri: lb://user-service       # 负载均衡到服务
uri: http://localhost:8080   # 直接URL
uri: https://example.com     # HTTPS地址
uri: ws://service:8080       # WebSocket

三、路由配置详解

完整路由定义

spring:
  cloud:
    gateway:
      routes:
        - id: user-service-v1
          uri: lb://user-service
          predicates:
            # 多重条件
            - Path=/api/v1/users/**
            - Method=GET,POST
            - Header=X-API-Version, v1
            - Query=type,internal
            - Cookie=session,.*
            - After=2024-01-01T00:00:00+08:00
            - Weight=user-group, 80
          filters:
            # 请求预处理
            - StripPrefix=2
            - PrefixPath=/internal
            - SetPath=/api/users/{segment}
            - RewritePath=/old/(?<path>.*), /new/$\{path}
            
            # 参数处理
            - AddRequestParameter=key,value
            - AddRequestHeader=X-Request-Id,12345
            - RemoveRequestHeader=Cookie
            
            # 响应处理
            - AddResponseHeader=X-Response-Time,${took}
            - DedupeResponseHeader=Set-Cookie
            
            # 熔断降级
            - name: CircuitBreaker
              args:
                name: userServiceCB
                fallbackUri: forward:/fallback/user
                statusCodes: 
                  - 500
                  - 502
                  - 503
                
            # 重试机制
            - name: Retry
              args:
                retries: 3
                statuses: SERVICE_UNAVAILABLE
                methods: GET
                backoff:
                  firstBackoff: 10ms
                  maxBackoff: 50ms
                  factor: 2
                  basedOnPreviousValue: false
                  
            # 请求大小限制
            - name: RequestSize
              args:
                maxSize: 5MB
                
            # 修改响应体
            - name: ModifyResponseBody
              args:
                in-class: String
                out-class: String
                rewrite-function: "#{@modifyResponseBody}"
                
          metadata:
            # 自定义元数据
            version: "1.0"
            timeout: 5000
            connect-timeout: 3000
            response-timeout: 10000
            max-auto-retries-next-server: 2
            max-auto-retries: 1
          order: 1

断言工厂详细配置

Path断言:

predicates:
  - Path=/api/users/{id}/**, /api/orders/{segment}

Header断言:

predicates:
  - name: Header
    args:
      header: X-Request-Id
      regexp: '\d+'

自定义断言:

predicates:
  - name: Custom
    args:
      name: myCustomPredicate
      arg1: value1
      arg2: value2

过滤器工厂详细配置

熔断器配置:

filters:
  - name: CircuitBreaker
    args:
      name: myCircuitBreaker
      fallbackUri: forward:/fallback
      statusCodes: 
        - 500
        - "BAD_GATEWAY"
        - "5xx"
      args:
        failureRateThreshold: 50
        slowCallDurationThreshold: "2s"
        permittedNumberOfCallsInHalfOpenState: 10
        slidingWindowSize: 100
        minimumNumberOfCalls: 10
        waitDurationInOpenState: "60s"

限流配置:

filters:
  - name: RequestRateLimiter
    args:
      key-resolver: "#{@userKeyResolver}"
      rate-limiter: "#{@redisRateLimiter}"
      deny-empty-key: true
      empty-key-status: 403
      
# Redis限流器配置
@Bean
public RedisRateLimiter redisRateLimiter() {
    return new RedisRateLimiter(10, 20, 1);
}

四、发现服务配置

服务发现自动路由

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          predicates:
            - name: Path
              args:
                pattern: "'/service/'+serviceId.toLowerCase()+'/**'"
          filters:
            - name: RewritePath
              args:
                regexp: "'/service/' + serviceId.toLowerCase() + '/(?<remaining>.*)'"
                replacement: "'/${remaining}'"

服务发现元数据路由

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          include-expression: metadata['version']=='v1'
          url-expression: "'http://'+serviceId.toLowerCase()+'.example.com'"

五、监控和指标配置

Micrometer指标

management:
  endpoints:
    web:
      exposure:
        include: health,info,gateway,metrics,prometheus
  metrics:
    tags:
      application: ${spring.application.name}
      
spring:
  cloud:
    gateway:
      metrics:
        enabled: true
        # 自定义标签
        tags:
          path: "${routeId}"
          method: "${request.method}"
          status: "${response.status}"

跟踪配置

spring:
  sleuth:
    gateway:
      enabled: true
    web:
      client:
        enabled: true
        
  zipkin:
    base-url: http://localhost:9411

六、安全配置

SSL/TLS配置

server:
  ssl:
    enabled: true
    key-store: classpath:keystore.p12
    key-store-password: changeit
    key-store-type: PKCS12
    key-alias: gateway
    key-password: changeit
    
spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          use-insecure-trust-manager: false
          handshake-timeout: 10000

安全头配置

spring:
  cloud:
    gateway:
      default-filters:
        - name: SecureHeaders
          args:
            xss-protection-header: 1; mode=block
            strict-transport-security: max-age=31536000 ; includeSubDomains
            x-frame-options: DENY
            content-type-options: nosniff
            referrer-policy: no-referrer
            content-security-policy: default-src 'self'

七、缓存和性能优化

路由缓存配置

spring:
  cloud:
    gateway:
      route:
        locator:
          cache:
            enabled: true
            initial-capacity: 100
            maximum-size: 1000
            ttl: 60s

连接池优化

spring:
  cloud:
    gateway:
      httpclient:
        pool:
          type: FIXED
          max-connections: 500
          max-idle-time: 30s
          max-life-time: 60s
          pending-acquire-timeout: 60s
          pending-acquire-max-count: 1000
          eviction-interval: 10s

八、完整配置示例

生产环境配置示例

spring:
  application:
    name: api-gateway
  
  cloud:
    gateway:
      # 全局配置
      default-filters:
        - AddRequestHeader=X-Gateway-Request-ID, ${random.uuid}
        - AddResponseHeader=X-Gateway-Response-Time, ${took}
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
      
      # 全局CORS
      globalcors:
        cors-configurations:
          '[/**]':
            allowed-origins: "*"
            allowed-methods: "*"
            allowed-headers: "*"
            max-age: 3600
            
      # HTTP客户端配置
      httpclient:
        pool:
          type: ELASTIC
          max-connections: 1000
          acquire-timeout: 45000
        connect-timeout: 5000
        response-timeout: 30000
        compression: true
        
      # 路由配置
      routes:
        - id: auth-service
          uri: lb://auth-service
          predicates:
            - Path=/auth/**
            - Method=POST
          filters:
            - StripPrefix=1
            - name: RequestRateLimiter
              args:
                key-resolver: "#{@ipKeyResolver}"
                redis-rate-limiter.replenishRate: 5
                redis-rate-limiter.burstCapacity: 10
            - CircuitBreaker=authService
            
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/users/**
            - Header=X-API-Token, .+
          filters:
            - StripPrefix=2
            - AddRequestHeader=X-Service-Version, v2
            - Retry=3
            
        - id: product-service
          uri: lb://product-service
          predicates:
            - Path=/api/products/**
            - Query=category
          filters:
            - StripPrefix=2
            - SetStatus=401, POST
            
      # 服务发现
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          
      # 指标
      metrics:
        enabled: true

# 监控端点
management:
  endpoints:
    web:
      exposure:
        include: health,info,gateway,metrics
  metrics:
    export:
      prometheus:
        enabled: true
  endpoint:
    health:
      show-details: always

九、自定义配置扩展

自定义过滤器

@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 前置处理
        ServerHttpRequest request = exchange.getRequest().mutate()
            .header("X-Custom-Header", "custom-value")
            .build();
            
        return chain.filter(exchange.mutate().request(request).build())
            .then(Mono.fromRunnable(() -> {
                // 后置处理
                Long startTime = exchange.getAttribute("startTime");
                if (startTime != null) {
                    Long endTime = System.currentTimeMillis();
                    System.out.println("请求耗时: " + (endTime - startTime) + "ms");
                }
            }));
    }
    
    @Override
    public int getOrder() {
        return -1;
    }
}

自定义断言工厂

@Component
public class CustomRoutePredicateFactory extends 
    AbstractRoutePredicateFactory<CustomRoutePredicateFactory.Config> {
    
    public CustomRoutePredicateFactory() {
        super(Config.class);
    }
    
    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            // 自定义断言逻辑
            return config.getValue().equals(exchange.getRequest().getHeaders().getFirst("X-Custom"));
        };
    }
    
    public static class Config {
        private String value;
        // getters and setters
    }
}

十、配置优化建议

  • 性能调优:

    • 根据负载调整连接池大小
    • 启用响应压缩
    • 合理设置超时时间
  • 高可用:

    • 配置多个相同服务实例
    • 设置合理的熔断和重试策略
    • 启用健康检查
  • 安全性:

    • 启用HTTPS
    • 配置安全响应头
    • 实施API限流
  • 可观测性:

    • 启用指标收集
    • 集成分布式跟踪
    • 配置详细日志

到此这篇关于spring-gateway配置的实现示例的文章就介绍到这了,更多相关spring gateway配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java中删除文件/文件夹的3种方法示例小结

    java中删除文件/文件夹的3种方法示例小结

    这篇文章主要介绍了java中删除文件/文件夹的3种方法示例小结,第一种是通过io删除文件,第二种是通过Files.walk删除文件,第三种是通过 Files.walkFileTree删除文件,本文结合示例代码给大家介绍的非常详细,需要的朋友参考下吧
    2023-10-10
  • idea打不开双击IDEA图标没反应的快速解决方案

    idea打不开双击IDEA图标没反应的快速解决方案

    这篇文章主要介绍了idea打不开双击IDEA图标没反应的快速解决方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Zookeeper Curator使用介绍

    Zookeeper Curator使用介绍

    curator是Netflix公司开源的⼀套Zookeeper客户端框架,和ZKClient⼀样,Curator解决了很多Zookeeper客户端非常底层的细节开发⼯作,包括连接重连,反复注册Watcher和NodeExistsException异常等,是最流行的Zookeeper客户端之⼀
    2022-09-09
  • SpringBoot中application.properties、application.yaml、application.yml区别

    SpringBoot中application.properties、application.yaml、applicati

    本文主要介绍了SpringBoot中application.properties、application.yaml、application.yml区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-04-04
  • SpringCloud超详细讲解Feign声明式服务调用

    SpringCloud超详细讲解Feign声明式服务调用

    Feign可以把Rest的请求进行隐藏,伪装成类似Spring MVC的Controller一样。不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做
    2022-06-06
  • maven无法依赖spring-cloud-stater-zipkin的解决方案

    maven无法依赖spring-cloud-stater-zipkin的解决方案

    这篇文章主要介绍了maven无法依赖spring-cloud-stater-zipkin如何解决,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • Java经典用法总结

    Java经典用法总结

    这篇文章主要介绍了Java经典用法总结,在本文中,尽量收集一些java最常用的习惯用法,特别是很难猜到的用法,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • Java实现注册登录跳转

    Java实现注册登录跳转

    这篇文章主要为大家详细介绍了Java实现注册登录跳转,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-06-06
  • SpringBoot整合sharding-jdbc实现自定义分库分表的实践

    SpringBoot整合sharding-jdbc实现自定义分库分表的实践

    本文主要介绍了SpringBoot整合sharding-jdbc实现自定义分库分表的实践,将通过自定义算法来实现定制化的分库分表来扩展相应业务,感兴趣的可以了解一下
    2021-11-11
  • Java如何获取当前时间的小时/分钟(实现方法)

    Java如何获取当前时间的小时/分钟(实现方法)

    文章介绍了Java获取当前时间的小时、分钟等的方法,包括两种常见方法,并鼓励读者继续浏览相关文章,感兴趣的朋友一起看看吧
    2025-02-02

最新评论