SpringCloud集成Zuul實(shí)現(xiàn)限流

pom.xml 添加依賴

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
     <groupId>com.marcosbarbero.cloud</groupId>
     <artifactId>spring-cloud-zuul-ratelimit</artifactId>
     <version>2.0.0.RELEASE</version>
</dependency>

配置application.yml

spring:
  application:
    name: gateway-server #服務(wù)名稱
  cloud:
    # 設(shè)置偏好網(wǎng)段
    inetutils:
      preferred-networks: 127.0.0.
    loadbalancer:
      retry:
        enabled: true
  jackson:
    date-format: yyyy-MM-dd
    joda-date-time-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
  redis:
    host: 127.0.0.1
    port: 6379
    timeout: 1000ms
    database: 0
    lettuce:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0
  zipkin:
    enabled: true
    base-url: http://zipkin-dashboard/


zuul:
  routes:
    user-service:
      path: /user/**
      serviceId: user-service
  add-host-header: true
  sensitive-headers: Access-Control-Allow-Origin,Access-Control-Allow-Methods
  strip-prefix: true
  ratelimit:
    # 開啟限流
    enabled: true
    # 存儲(chǔ)方式
    repository: REDIS
    # 限流策略
    policies:
      # 指定限流服務(wù)
      user-service:
        # 每個(gè)周期內(nèi)請(qǐng)求次數(shù)
        limit: 3
        # 單位時(shí)間內(nèi)允許訪問的總時(shí)間
        quota: 30
        # 周期時(shí)間
        refresh-interval: 60
        # 限流方式 USER 根據(jù)用戶;ORIGIN 原始請(qǐng)求;URL 請(qǐng)求地址;
        type: ORIGIN
server:
  port: 9001    # 端口號(hào)

eureka:
  client:
    serviceUrl:
      # 服務(wù)器注冊(cè)/獲取服務(wù)器的zone
      defaultZone: http://127.0.0.1:9000/eureka/
    healthcheck:
      enabled: true
  instance:
    prefer-ip-address: true

配置說明

zuul.ratelimit.repository 存儲(chǔ)方式

  • InMemoryRateLimiter - 使用 ConcurrentHashMap作為數(shù)據(jù)存儲(chǔ)
  • ConsulRateLimiter - 使用 Consul 作為數(shù)據(jù)存儲(chǔ)
  • RedisRateLimiter - 使用 Redis 作為數(shù)據(jù)存儲(chǔ)
  • SpringDataRateLimiter - 使用 數(shù)據(jù)庫(kù) 作為數(shù)據(jù)存儲(chǔ)

zuul.ratelimit.policies 限流策略

limit 每個(gè)周期內(nèi)請(qǐng)求次數(shù)
quota 單位時(shí)間內(nèi)允許訪問的總時(shí)間
refresh-interval 周期時(shí)間
type 限流方式 USER 根據(jù)用戶;ORIGIN 原始請(qǐng)求;URL 請(qǐng)求地址;

正常訪問

正常訪問

超出次數(shù)訪問


超出次數(shù)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容