前言
近日开发一个日志接口,供其他系统通过 webservice 进行调用。考虑到并发,多线程决定使用阻塞队列实现日志接口。记录实现的过程,供大家参考,对阻塞队列不了解的,可以参照上一篇博文。
实现阻塞队列
-
public class RemoteUpgradeLogQueue {
-
-
private static RemoteUpgradeLogQueue remoteUpgradeLogQueue = new RemoteUpgradeLogQueue();
-
-
//定义一个阻塞队列
-
-
private <u>BlockingQueue</u> blockingQueue = new
-
LinkedBlockingQueue<>();
-
-
private RemoteUpgradeLogQueue(){}
-
-
public static RemoteUpgradeLogQueue getInstance(){
-
-
return remoteUpgradeLogQueue;
-
-
}
-
-
public Boolean push(RemoteUpgradeLogInfo
-
remoteUpgradeLogInfo){
-
-
return <u>this</u><u>.</u><u>blockingQueue</u><u>.add(</u><u>remoteUpgradeLogInfo</u><u>)</u>;
-
-
}
-
-
public RemoteUpgradeLogInfo pop(){
-
-
RemoteUpgradeLogInfo remoteUpgradeLogInfo = null;
-
-
try {
-
-
remoteUpgradeLogInfo = (RemoteUpgradeLogInfo)
-
this.blockingQueue.take();
-
-
} catch (InterruptedException e) {
-
-
System.out.println("从队列中取出日志错误!");
-
-
}
-
-
return remoteUpgradeLogInfo;
-
-
}
-
-
public int size(){
-
-
return this.blockingQueue.size();
-
-
}
-
-
}
定义消费者
service调用的方法就为具体的处理日志的方法
-
@Component
-
-
public class DealRemoteUpgradeLogQueue {
-
-
-
-
@Autowired
-
-
private RemoteUpgradeLogService remoteUpgradeLogService;
-
-
-
-
@PostConstruct
-
-
public void startLogThread(){
-
-
ExecutorService e = Executors.newFixedThreadPool(1);
-
-
e.submit(new PopLogInfo(remoteUpgradeLogService));
-
-
}
-
-
-
-
class PopLogInfo implements Runnable {
-
-
RemoteUpgradeLogService remoteUpgradeLogService;
-
-
-
-
public PopLogInfo(RemoteUpgradeLogService
-
remoteUpgradeLogService) {
-
-
this.remoteUpgradeLogService =
-
remoteUpgradeLogService;
-
-
}
-
-
-
-
@Override
-
-
public void run() {
-
-
while (true) {
-
-
try {
-
-
RemoteUpgradeLogInfo remoteUpgradeLogInfo = RemoteUpgradeLogQueue.getInstance().pop();
-
-
if(remoteUpgradeLogInfo!=null){
-
-
remoteUpgradeLogService.saveLogInfo(remoteUpgradeLogInfo);
-
-
}
-
-
} catch (Exception e) {
-
-
e.printStackTrace();
-
-
}
-
-
}
-
-
}
-
-
}
-
}
实现生产者
生产者直接往对列中 push 即可。
RemoteUpgradeLogQueue.getInstance().push(remoteUpgradeLogInfo);
评论(0)