您的位置:首页 > 产品设计 > UI/UE

BlockQueue使用之简单应用

2015-12-22 00:00 453 查看
摘要: 最近在搞爬虫,其中有一项统计功能不仅让我计数,还要我存一下URL,首先是无语,但是还是要实现
然后最后就想到了将URL临时存储到队列中,然后再有线程读取写入Log,说的好像挺简单但是
对于我这种小菜,BlockQueue这里堵了好几次.........

当然试了好几种,包括用add方法抛异常,用offer方法判断BlockQueue有没有满,但是感觉没有从根本上解决问题,于是就用了下面的方法,设置队列的容量是1000,当达到900的时候,就启用日志线程读取。

/**

* 存储计数的信息

* @throws InterruptedException

*/

@Override

public void add(String counter, String url) throws Exception {

if( true == urlInputLogFile ){

BlockingQueue<String> blockingQueue = countersMap.get(counter);

if(null == blockingQueue){

blockingQueue = new ArrayBlockingQueue<String>(1000);

blockingQueue.put(url);

countersMap.put(counter, blockingQueue);

this.add(counter);

}else{

this.add(counter);

if(blockingQueue.size()==900){ //容量是1000等到满去写会阻塞

String date = DateFormatUtils.format(new Date(), "yyyyMMdd");

String name = counter+date+".log";

File rootPath = new File(this.getClass().getResource("/").getPath());

File path = new File(rootPath, urlInputLogFilePath);

if(!path.exists()){

path.mkdirs();

}

File file = new File(path,name);

if(!file.exists()){

file.createNewFile();

}

redisUrlLog.setLogFile(file);

redisUrlLog.setQueue(blockingQueue);

blockingQueue.add(url); //这里要再有异常,只好抛了,要不然就堵啊

countersMap.put(counter, blockingQueue);

}else{

countersMap.put(counter, blockingQueue);

}

}

}else{

this.add(counter);

}

}

以上供大家一起学习有什么好想法,可以留言相互沟通。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: