当然试了好几种,包括用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);
}
}
以上供大家一起学习有什么好想法,可以留言相互沟通。
本文介绍了一种使用Java的BlockingQueue实现日志记录的方法。当队列达到一定容量时,启动线程将日志写入文件,避免了因队列满而导致的阻塞问题。文中还探讨了如何通过异常处理确保数据不丢失。

1万+

被折叠的 条评论
为什么被折叠?



