Java:构建简单的速率限制器

您所在的位置:网站首页 java下载限速的实现 Java:构建简单的速率限制器

Java:构建简单的速率限制器

2024-05-30 14:37| 来源: 网络整理| 查看: 265

速率限制

现实世界中的用户是残暴的,并且没耐心,充满着各种不确定性。在高并发系统中,可能会出现服务器被虚假请求轰炸的情况,因此您可能希望控制这种情况。

一些实际使用情形可能如下所示:

API配额管理-作为提供者,您可能希望根据用户的付款情况限制向服务器发出API请求的速率。这可以在客户端或服务端实现。

安全性-防止DDOS攻击。

成本控制--这对服务方甚至客户方来说都不是必需的。如果某个组件以非常高的速率发出一个事件,它可能有助于控制它,它可能有助于控制从客户端发送的遥测。

限速处理时的选项

根据我们处理的请求/事件类型,可能会发生以下情况:

我们可以放弃额外的请求

我们可以选择让请求等待,直到系统将它们降低到预定义的速率。

常用限速算法

令牌桶算法

漏桶算法

我们将不深入讨论这些算法的内部细节,因为这超出了本文的范围。

我们将以令牌桶算法为中心。其要求如下。

令牌桶算法基于以固定速率添加令牌的固定容量桶的类比。在允许API继续之前,将检查桶,以查看它当时是否包含至少一个令牌。如果令牌存在,则进行API调用。如果不是,则丢弃该消息/或使其等待。

需求

应该能够接受每秒所需的(TPS)事务或速率。

如果超过我们定义的比率,则应放弃交易。

应该在同时发生的情况下起作用。

高级功能(在后续文章中实现)

应该能够平滑突发的请求。例如,如果我们将TPS定义为5,并且所有五个请求都在同一时刻到达,那么它应该能够以固定的时间间隔将它们排成一行,即以200ms的时间间隔执行每个请求。它需要一个内部定时电路。

如果我们的TPS为5,并且在其中一个1秒的时段中,我们在下一秒只使用3个代币,那么我们应该能够提供5+2 = 7个代币作为奖励。但速率为每个令牌1/7(142.28ms)。奖金不应结转到下一个插槽。

让我们首先定义我们的 速率限制器:

/** * Rate limiter helps in limiting the rate of execution of a piece of code. The rate is defined in terms of * TPS(Transactions per second). Rate of 5 would suggest, 5 transactions/second. Transaction could be a DB call, API call, * or a simple function call. *

* Every {@link RateLimiter} implementation should implement either {@link RateLimiter#throttle(Code)} or, {@link RateLimiter#enter()}. * They can also choose to implement all. *

* {@link Code} represents a piece of code that needs to be rate limited. It could be a function call, if the code to be rate limited * spreads across multiple functions, we need to use entry() and exit() contract. */publicinterfaceRateLimiter{ /** * Rate limits the code passed inside as an argument. * * @param code representation of the piece of code that needs to be rate limited. * @return true if executed, false otherwise. */booleanthrottle(Code code); /** * When the piece of code that needs to be rate limited cannot be represented as a contiguous * code, then entry() should be used before we start executing the code. This brings the code inside the rate * limiting boundaries. * * @return true if the code will execute and false if rate limited. *



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3