Spring Cloud Gateway 原生的介面限流該怎麼玩
作者:冷冷gg
來源:https://my.oschina.net/giegie/blog/1838560
關於 Spring Cloud Gateway
SpringCloudGateway是Spring官方基於Spring 5.0,Spring Boot 2.0和Project Reactor等技術開發的閘道器,Spring雲網關旨在提供一種簡單而有效的路由API的方法。
Spring Cloud Gateway作為Spring Cloud生態系中的閘道器,目標是替代Netflix ZUUL,其不僅提供統一的路由方式,並且基於Filter鏈的方式提供了閘道器基本的功能,例如:安全,監控/埋點,和限流等。
zuul如何實現多維度限流
開始Gateway 限流
POM 依賴
<!--spring cloud gateway依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--基於 reactive stream 的redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
配置按照請求IP 的限流
spring:
cloud:
gateway:
routes:
- id: requestratelimiter_route
uri: lb://pigx-upms
order: 10000
predicates:
- Path=/admin/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 1 # 令牌桶的容積
redis-rate-limiter.burstCapacity: 3 # 流速 每秒
key-resolver: "#{@remoteAddrKeyResolver}" #SPEL表示式去的對應的bean
- StripPrefix=1
配置bean,多維度限流量的入口
/**
* 自定義限流標誌的key,多個維度可以從這裡入手
* exchange物件中獲取服務ID、請求資訊,使用者資訊等
*/
@Bean
KeyResolver remoteAddrKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
OK 完成。
壓力測試
併發5個執行緒。
Redis 資料變化
我們使用redis的monitor 命令,實時檢視redis 的操作情況。 會發現在redis中會操作兩個key
requestratelimiter.{xxx}.timestamp
requestratelimiter.{xxx}.tokens
實現原理
Spring Cloud Gateway 預設實現 Redis限流,如果擴充套件只需要實現ratelimter介面即可。
RedisRateLimter 的核心程式碼,判斷是否取到令牌的實現,通過呼叫 redis的LUA 指令碼。
publicMono<Response> isAllowed(String routeId, String id) {
Config routeConfig = getConfig().getOrDefault(routeId, defaultConfig);
int replenishRate = routeConfig.getReplenishRate();
int burstCapacity = routeConfig.getBurstCapacity();
try {
List<String> keys = getKeys(id);
returns unixtime in seconds.
List<String> scriptArgs = Arrays.asList(replenishRate + "", burstCapacity + "",
Instant.now().getEpochSecond() + "", "1");
// 這裡是核心,執行redis 的LUA 指令碼。
Flux<List<Long>> flux =
this.redisTemplate.execute(this.script, keys, scriptArgs);
return flux.onErrorResume(throwable -> Flux.just(Arrays.asList(1L, -1L)))
.reduce(newArrayList<Long>(), (longs, l) -> {
longs.addAll(l);
return longs;
}) .map(results -> {
boolean allowed = results.get(0) == 1L;
Long tokensLeft = results.get(1);
Response response = newResponse(allowed, getHeaders(routeConfig, tokensLeft));
if (log.isDebugEnabled()) {
log.debug("response: " + response);
}
return response;
});
}
catch (Exception e) {
log.error("Error determining if user allowed from redis", e);
}
returnMono.just(newResponse(true, getHeaders(routeConfig, -1L)));
}
LUA 指令碼
-END-
近期熱文:
關注我
點選“閱讀原文”,看本號其他精彩內容
相關推薦
Spring Cloud Gateway 自定義限流
在使用Spring Cloud Gateway限流功能時官網提供的限流中的流速以及桶容量是針對所有策略的,意思是隻要配置上那麼所有的都是一樣的,不能根據不同的型別配置不同的引數,例如:A渠道、B渠道,若配置上replenishRate(流速)和burstCapacity(令牌桶容量),那
spring cloud gateway(實現限流)
spring cloud gateway(實現限流) 限流一般有兩個實現方式,令牌桶和漏桶 令牌桶是初始化令牌(容器)的個數,通過拿走裡邊的令牌就能通過
Spring Cloud Gateway 原生的介面限流該怎麼玩
作者:冷冷gg來源:https://my.oschina.net/giegie/blog/183
Spring Cloud Zuul中路由限流配置
Zuul配置: pom.xml 新增 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-clou
Spring Cloud Alibaba使用Sentinel限流_四
浪費了“黃金五年”的Java程式設計師,還有救嗎? >>>
Spring Cloud Alibaba | Sentinel: 服務限流基礎篇
目錄 Spring Cloud Alibaba | Sentinel: 服務限流基礎篇 1. 簡介 2. 定義資源 2.1 主流框架的預設適配 2.2 丟擲異常的方式定義資源
Spring Cloud Alibaba 之 Sentinel 限流規則和控制檯例項
這一節我們通過一個簡單的例項,學習Sentinel的基本應用。 一、Sentinel 限流核心概念 在學習Sentinel的具體應用之前,我們先來了解一下Sentinel中兩個核心的概念,資源和規則。 資源 資源 是 Sentinel 中的核心概念之一。既然是限流,或者系統保護,那麼是針對什麼做限流?保護
Spring Cloud Gateway 結合配置中心限流
serve ffi cep limit true 關心 lean 作用 left 前言 假設你領導給你安排了一個任務,具體需求如下: 針對具體的接口做限流 不同接口限流的力度可以不同 可以動態調整限流配置,實時生效 如果你接到上面的任務,你會怎麽去設計+實現呢?
spring cloud gateway(三、實現限流)
限流一般有兩個實現方式,令牌桶和漏桶 金牌桶是初始化令牌(容器)的個數,通過拿走裡邊的令牌就能通過, 沒有令牌不能報錯,可以設定向容器中增加令牌的速度和最大個數 漏桶是向裡邊放入請求,當請求數量達到最大值後,丟棄,漏桶中的資料以一定速度流出,沒有則不流出 金牌桶實現方式如下: pom <dependen
spring cloud gateway 之限流篇
轉載請標明出處: www.fangzhipeng.com 本文出自方誌朋的部落格 在高併發的系統中,往往需要在系統中做限流,一方面是為了防止大量的請求使伺服器過載,導致服務不可用,另一方面是為了防止網路攻擊。 常見的限流方式,比如Hystrix適用執行緒池隔離,超過執行緒池的負載,走熔斷的邏輯。
Spring Cloud Gateway 擴充套件支援動態限流
之前分享過 一篇 《Spring Cloud Gateway 原生的介面限流該怎麼玩》, 核心是依賴Spring Cloud G
Spring Cloud實戰 | 第十一篇:Spring Cloud Gateway 閘道器實現對RESTful介面許可權控制和按鈕許可權控制
## 一. 前言 hi,大家好,這應該是農曆年前的關於開源專案[有來商城](https://github.com/hxrui) 的最後一篇文章了。 [有來商城](https://github.com/hxrui) 是基於 Spring Cloud OAuth2 + Spring Cloud Gateway
Spring Cloud實戰 | 第十一篇:Spring Cloud Gateway閘道器實現對RESTful介面許可權和按鈕許可權細粒度控制
## 一. 前言 hi,大家好,這應該是農曆年前的關於開源專案[有來商城](https://github.com/hxrui) 的最後一篇文章了。 [有來商城](https://github.com/hxrui) 是基於 Spring Cloud OAuth2 + Spring Cloud Gateway
003-spring cloud gateway-概述、基本原理、Route Predicate Factory
默認端口 子網掩碼 彈性 技術 link exc ring ipv4 路由 一、概述 前提條件:Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway旨在提供一種簡單而有效的方式來路由到
004-spring cloud gateway-GatewayFilter Factories
ons 系列 iter 簡單 參數 ram move 1.5 .html 一、GatewayFilter Factories 路由過濾器允許以某種方式修改傳入的HTTP請求或傳出的HTTP響應。路徑過濾器的範圍限定為特定路徑。 Spring Cloud Gateway
007-spring cloud gateway-GatewayAutoConfiguration核心配置-RouteDefinition初始化加載
hand 配置信息 包裝類 eid override repo shm 配置路由 本地緩存 一、RouteDefinitionLocator 在Spring-Cloud-Gateway的GatewayAutoConfiguration初始化加載中會加載RouteDef
API網關性能比較:NGINX vs. ZUUL vs. Spring Cloud Gateway vs. Linkerd(轉)
master 優點 進程間 ring 每次 32gb 性能比較 servlet 以及 前幾天拜讀了 OpsGenie 公司(一家致力於 Dev & Ops 的公司)的資深工程師 Turgay ?elik 博士寫的一篇文章(鏈接在文末),文中介紹了他們最初也是采用 N
spring cloud gateway GlobalFilter設定返回HTTPcode和response
@Component public class AuthGlobalFilterFilter implements GlobalFilter, Ordered { private static final String HEADER_KEY= "KEY"; private sta
Zuul and Spring Cloud Gateway – Config file
zuul: zuul: routes: demo: sensitiveHeaders: Access-Control-Allow-Origin,Access-Control-Allow-Methods path: /d
Java 介面限流
目錄: 限流原理 知識點 具體實現 結語 內容: 1、限流原理 -- 令牌桶演算法 令牌桶演算法的原理是系統會以一個恆定的速度(每秒生成一個令牌)往桶裡放入令牌。當有訪問者(針對於 IP)要訪問介面時,則需要先從桶裡獲取一個令