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ù)