Ratelimiter-限流器的使用
RateLimiter
限流器的使用,一般用于接口qps或者某种资源的访问速率的限制
-
引入依赖
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>25.1-jre</version> </dependency>
-
代码实战,限制某个接口的qps为3
public class RateLimiterDemo { //新建一个每秒限制3个的令牌桶 public static RateLimiter rateLimiter = RateLimiter.create(3,1, TimeUnit.SECONDS); public static ExecutorService executor = Executors.newFixedThreadPool(10); public static void main(String[] args) { for (int i = 0; i < 10; i++) { executor.execute(() -> { //获取令牌桶中一个令牌,最多等待10秒 if (rateLimiter.tryAcquire(1, 4, TimeUnit.SECONDS)) { testInterface(); System.out.println(Thread.currentThread().getName()+" "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); }else { System.out.println("请求频繁,限流住了"); } }); } } public static void testInterface(){ //to do //假设这个是上游接口,最大支持qps为3 System.out.println("访问接口成功"); } }
结果:
参考:
本文来自博客园,作者:orangeScc,转载请注明原文链接:https://www.cnblogs.com/ashScc/p/15669189.html