Contents

爬虫限速Demo:控制接口调用的速率

Contents

使用guava漏桶算法实现速率控制

    @Test
    public void testRateLimiterParallel() throws Exception {

        Stopwatch started = Stopwatch.createStarted();
        ExecutorService executorService = Executors.newFixedThreadPool(140);
        RateLimiter rateLimiter = RateLimiter.create(140);//创建限流器 每秒只能通过140个请求
        ArrayList<CompletableFuture> objects = Lists.newArrayList();
        IntStream.range(0, 200).forEach(item -> {
            rateLimiter.acquire();
            System.out.println("等待:"+rateLimiter.acquire());
            System.out.println("等待结束"+item);
            //多线程模拟请求
            CompletableFuture<Void> cFeature = CompletableFuture.runAsync(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(200);
                    System.out.println("输出" + item + ": 当前秒数:" + LocalDateTime.now().getSecond());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, executorService);
            objects.add(cFeature);
        });
        CompletableFuture.allOf(objects.toArray(new CompletableFuture[objects.size()])).join();
        System.out.println("执行完毕");
        started.stop();
        long elapsed = started.elapsed(TimeUnit.MILLISECONDS);
        System.out.println("耗时:" + elapsed);

    }