面试题目:如何实现限流
思路: 限制同一时间段的请求数量,即使用计数器来限制请求的数量。
请求开始加1,请求结束减1;
@RestController public class Demo1_CounterTest { Counter counter = new CounterBasic(); int limit = 3000; @RequestMapping("/hello") public void hello() { counter.incr(); // 请求超过限制 if (counter.get() > limit) { // 限流 return; } try { // 业务逻辑 } finally { // 处理完毕, 数量减一 counter.decr(); } } }
原文:https://www.cnblogs.com/Jomini/p/13621757.html