最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring-gateway配置的實(shí)現(xiàn)示例

 更新時(shí)間:2025年12月24日 08:25:16   作者:JavaBoy_XJ  
本文詳細(xì)介紹了Spring?Cloud?Gateway的核心配置結(jié)構(gòu),分為全局配置和路由配置兩大部分,下面就來詳細(xì)的介紹一下spring-gateway配置的實(shí)現(xiàn)示例,感興趣的可以了解一下

一、核心配置結(jié)構(gòu)總覽

spring:
  cloud:
    gateway:
      # 1. 全局配置
      default-filters: []
      globalcors: {}
      httpclient: {}
      metrics: {}
      
      # 2. 路由配置
      routes:
        - id: 
          uri: 
          predicates: []
          filters: []
          metadata: {}
          order: 0
          
      # 3. 發(fā)現(xiàn)服務(wù)配置
      discovery:
        locator:
          enabled: false
          
      # 4. 路由定義存儲(chǔ)
      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  # 最大連接數(shù)
          acquire-timeout: 45000 # 獲取連接超時(shí)(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
          
        # 響應(yīng)壓縮
        compression: true

WebFlux配置

spring:
  cloud:
    gateway:
      # WebFlux配置
      httpclient:
        # 響應(yīng)式客戶端配置
        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       # 負(fù)載均衡到服務(wù)
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:
            # 請(qǐng)求預(yù)處理
            - StripPrefix=2
            - PrefixPath=/internal
            - SetPath=/api/users/{segment}
            - RewritePath=/old/(?<path>.*), /new/$\{path}
            
            # 參數(shù)處理
            - AddRequestParameter=key,value
            - AddRequestHeader=X-Request-Id,12345
            - RemoveRequestHeader=Cookie
            
            # 響應(yīng)處理
            - AddResponseHeader=X-Response-Time,${took}
            - DedupeResponseHeader=Set-Cookie
            
            # 熔斷降級(jí)
            - name: CircuitBreaker
              args:
                name: userServiceCB
                fallbackUri: forward:/fallback/user
                statusCodes: 
                  - 500
                  - 502
                  - 503
                
            # 重試機(jī)制
            - name: Retry
              args:
                retries: 3
                statuses: SERVICE_UNAVAILABLE
                methods: GET
                backoff:
                  firstBackoff: 10ms
                  maxBackoff: 50ms
                  factor: 2
                  basedOnPreviousValue: false
                  
            # 請(qǐng)求大小限制
            - name: RequestSize
              args:
                maxSize: 5MB
                
            # 修改響應(yīng)體
            - name: ModifyResponseBody
              args:
                in-class: String
                out-class: String
                rewrite-function: "#{@modifyResponseBody}"
                
          metadata:
            # 自定義元數(shù)據(jù)
            version: "1.0"
            timeout: 5000
            connect-timeout: 3000
            response-timeout: 10000
            max-auto-retries-next-server: 2
            max-auto-retries: 1
          order: 1

斷言工廠詳細(xì)配置

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

過濾器工廠詳細(xì)配置

熔斷器配置:

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);
}

四、發(fā)現(xiàn)服務(wù)配置

服務(wù)發(fā)現(xiàn)自動(dòng)路由

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}'"

服務(wù)發(fā)現(xiàn)元數(shù)據(jù)路由

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

五、監(jiān)控和指標(biāo)配置

Micrometer指標(biāo)

management:
  endpoints:
    web:
      exposure:
        include: health,info,gateway,metrics,prometheus
  metrics:
    tags:
      application: ${spring.application.name}
      
spring:
  cloud:
    gateway:
      metrics:
        enabled: true
        # 自定義標(biāo)簽
        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'

七、緩存和性能優(yōu)化

路由緩存配置

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

連接池優(yōu)化

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

八、完整配置示例

生產(chǎn)環(huán)境配置示例

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
            
      # 服務(wù)發(fā)現(xiàn)
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
          
      # 指標(biāo)
      metrics:
        enabled: true

# 監(jiān)控端點(diǎn)
management:
  endpoints:
    web:
      exposure:
        include: health,info,gateway,metrics
  metrics:
    export:
      prometheus:
        enabled: true
  endpoint:
    health:
      show-details: always

九、自定義配置擴(kuò)展

自定義過濾器

@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("請(qǐng)求耗時(shí): " + (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
    }
}

十、配置優(yōu)化建議

  • 性能調(diào)優(yōu):

    • 根據(jù)負(fù)載調(diào)整連接池大小
    • 啟用響應(yīng)壓縮
    • 合理設(shè)置超時(shí)時(shí)間
  • 高可用:

    • 配置多個(gè)相同服務(wù)實(shí)例
    • 設(shè)置合理的熔斷和重試策略
    • 啟用健康檢查
  • 安全性:

    • 啟用HTTPS
    • 配置安全響應(yīng)頭
    • 實(shí)施API限流
  • 可觀測(cè)性:

    • 啟用指標(biāo)收集
    • 集成分布式跟蹤
    • 配置詳細(xì)日志

到此這篇關(guān)于spring-gateway配置的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)spring gateway配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

崇礼县| 兴和县| 将乐县| 晋城| 遂平县| 东城区| 合山市| 紫阳县| 澄城县| 道真| 新和县| 娱乐| 车险| 清丰县| 山东省| 泰顺县| 东台市| 湄潭县| 绵竹市| 娄底市| 明光市| 永修县| 青冈县| 通江县| 鲁山县| 河南省| 普定县| 郓城县| 秀山| 民丰县| 隆化县| 屯昌县| 金湖县| 安宁市| 额济纳旗| 元谋县| 辽中县| 余江县| 南靖县| 冷水江市| 合川市|