限制方法在N秒内调用M个请求 [英] Throttling method calls to M requests in N seconds

查看:153
本文介绍了限制方法在N秒内调用M个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个组件/类来限制某些方法的执行到N秒内的最大M次调用(或ms或nanos,无所谓)。

I need a component/class that throttles execution of some method to maximum M calls in N seconds (or ms or nanos, does not matter).

在其他我需要确保我的方法在N秒的滑动窗口中执行不超过M次。

In other words I need to make sure that my method is executed no more than M times in a sliding window of N seconds.

如果你不知道现有的课程,请随意发布您的解决方案/想法如何实现这一点。

If you don't know existing class feel free to post your solutions/ideas how you would implement this.

推荐答案

我使用环形缓冲区。每次调用该方法时,检查最旧的条目,如果它小于N过去几秒钟,你执行并添加另一个条目,否则你会睡觉时差。

I'd use a ring buffer of timestamps with a fixed size of M. Each time the method is called, you check the oldest entry, and if it's less than N seconds in the past, you execute and add another entry, otherwise you sleep for the time difference.

这篇关于限制方法在N秒内调用M个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆