记录异常日志(默认情况下,线程池会捕获任务抛出的所有异常,但是不做任何处理)

master
geekymv 6 years ago committed by Limy
parent 8040e0d4c9
commit aad585bdff

@ -1,9 +1,14 @@
package com.ruoyi.common.config.thread; package com.ruoyi.common.config.thread;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@ -16,6 +21,8 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration @Configuration
public class ThreadPoolConfig public class ThreadPoolConfig
{ {
private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);
// 核心线程池大小 // 核心线程池大小
private int corePoolSize = 50; private int corePoolSize = 50;
@ -48,6 +55,25 @@ public class ThreadPoolConfig
protected ScheduledExecutorService scheduledExecutorService() protected ScheduledExecutorService scheduledExecutorService()
{ {
return new ScheduledThreadPoolExecutor(corePoolSize, return new ScheduledThreadPoolExecutor(corePoolSize,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()); new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if(t != null) {
log.error(t.getMessage());
}
}
};
} }
} }

Loading…
Cancel
Save