java爬虫如何休眠
Java爬虫休眠的实现方法
在Java爬虫中,合理的休眠策略可以避免对目标网站造成过大压力,防止被封禁。以下是几种常见的休眠实现方式:
Thread.sleep()方法
使用Thread.sleep()是最直接的休眠方式,让当前线程暂停执行指定的毫秒数:
try {
// 休眠5秒
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
随机休眠时间
固定的休眠间隔容易被识别为爬虫行为,可以引入随机性:
Random random = new Random();
int sleepTime = random.nextInt(3000) + 2000; // 2-5秒随机休眠
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
定时任务调度
使用ScheduledExecutorService可以实现更复杂的调度逻辑:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(() -> {
// 爬虫任务代码
}, 0, 10, TimeUnit.SECONDS); // 每10秒执行一次
基于请求间隔的休眠
记录上次请求时间,确保两次请求之间有足够间隔:
long lastRequestTime = 0;
int minInterval = 3000; // 最小间隔3秒
long currentTime = System.currentTimeMillis();
if (currentTime - lastRequestTime < minInterval) {
try {
Thread.sleep(minInterval - (currentTime - lastRequestTime));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lastRequestTime = System.currentTimeMillis();
使用爬虫框架的休眠功能
主流爬虫框架如WebMagic内置了休眠控制:

// WebMagic示例
Spider.create(new MyPageProcessor())
.addUrl("http://example.com")
.setScheduler(new QueueScheduler()
.setDuplicateRemover(new BloomFilterDuplicateRemover(10000000)))
.thread(5)
.setDownloader(new HttpClientDownloader()
.setSleepTime(1000)) // 设置请求间隔1秒
.run();
注意事项
- 休眠时间应根据目标网站的robots.txt要求和服务器负载情况合理设置
- 对于高频访问可能导致IP被封的情况,建议结合代理IP池使用
- 在分布式爬虫中,需要协调不同节点的访问频率






