优化线程池执行任务异常时的日志记录

This commit is contained in:
风雨行
2023-05-31 13:30:20 +08:00
parent e0963e88bd
commit bb37026f0a
3 changed files with 12 additions and 12 deletions

View File

@@ -46,7 +46,7 @@ public class ThreadPoolConfig implements AsyncConfigurer {
executor.setQueueCapacity(200);
executor.setThreadNamePrefix("mallchat-executor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了调用线程执行,认为重要任务
executor.setThreadFactory(new MyThreadFactory(executor.getThreadNamePrefix()));
executor.setThreadFactory(new MyThreadFactory(executor));
executor.initialize();
return executor;
}
@@ -59,7 +59,7 @@ public class ThreadPoolConfig implements AsyncConfigurer {
executor.setQueueCapacity(1000);//支持同时推送1000人
executor.setThreadNamePrefix("websocket-executor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());//满了直接丢弃,默认为不重要消息推送
executor.setThreadFactory(new MyThreadFactory(executor.getThreadNamePrefix()));
executor.setThreadFactory(new MyThreadFactory(executor));
executor.initialize();
return executor;
}

View File

@@ -4,21 +4,23 @@ import com.abin.mallchat.common.common.handler.GlobalUncaughtExceptionHandler;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadFactory;
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class MyThreadFactory implements ThreadFactory {
private String name;
public class MyThreadFactory implements ThreadFactory {
private ThreadFactory factory;
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(new GlobalUncaughtExceptionHandler(name));
Thread thread =factory.newThread(r);
thread.setUncaughtExceptionHandler(new GlobalUncaughtExceptionHandler());
thread.setDaemon(false);
thread.setPriority(5);
return thread;
}
}

View File

@@ -5,14 +5,12 @@ import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class GlobalUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private String name;
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("线程池名称:[{}],错误信息如下:",name);
log.error("{} task execute is error",t.getName());
e.printStackTrace();
}