spring-cloud-zuul-ratelimit是和zuul整合提供分佈式限流策略的擴展,只需在yaml中配置幾行配置,就可以使應用支持限流git
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
複製代碼
服務粒度 (默認配置,當前服務模塊的限流控制)github
用戶粒度 (詳細說明,見文末總結)spring
ORIGIN粒度 (用戶請求的origin做爲粒度控制)數據庫
接口粒度 (請求接口的地址做爲粒度控制)安全
以上粒度自由組合,又能夠支持多種狀況。bash
若是還不夠,自定義RateLimitKeyGenerator實現。數據結構
//默認實現
public String key(final HttpServletRequest request, final Route route, final RateLimitProperties.Policy policy) {
final List<Type> types = policy.getType();
final StringJoiner joiner = new StringJoiner(":");
joiner.add(properties.getKeyPrefix());
if (route != null) {
joiner.add(route.getId());
}
if (!types.isEmpty()) {
if (types.contains(Type.URL) && route != null) {
joiner.add(route.getPath());
}
if (types.contains(Type.ORIGIN)) {
joiner.add(getRemoteAddr(request));
}
// 這個結合文末總結。
if (types.contains(Type.USER)) {
joiner.add(request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : ANONYMOUS_USER);
}
}
return joiner.toString();
}
複製代碼
zuul:
ratelimit:
key-prefix: your-prefix
enabled: true
repository: REDIS
behind-proxy: true
policies:
myServiceId:
limit: 10
quota: 20
refresh-interval: 30
type:
- user
複製代碼
以上配置意思是:30秒內容許10個訪問,而且要求總請求時間小於20秒框架
yaml配置:分佈式
zuul:
ratelimit:
key-prefix: pig-ratelimite
enabled: true
repository: REDIS
behind-proxy: true
policies:
pig-admin-service:
limit: 2
quota: 1
refresh-interval: 3
複製代碼
動態圖 ↓↓↓↓↓ 字體
Redis 中數據結構 注意紅色字體