ThreadPoolConfig.java
import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.*; /** * 线程池配置类 **/ @Configuration @Slf4j public class ThreadPoolConfig { /** * 核心线程池大小 */ private int corePoolSize = 50; /** * 执行定时任务 */ @Bean(name = "scheduledExecutorService") protected ScheduledExecutorService scheduledExecutorService() { return new ScheduledThreadPoolExecutor(corePoolSize, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); printException(r, t); } }; } /** * 打印线程异常信息 */ public static void printException(Runnable r, Throwable t) { if (t == null && r instanceof Future<?>) { try { Future<?> future = (Future<?>) r; if (future.isDone()) { future.get(); } } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (t != null) { log.error(t.getMessage(), t); } } }
AsyncManager.java (SpringUtils.java 参考:https://www.cnblogs.com/pxblog/p/15065785.html)
import lombok.extern.slf4j.Slf4j; import java.util.TimerTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * 异步任务管理器 */ @Slf4j public class AsyncManager { /** * 操作延迟10毫秒执行 */ private final int OPERATE_DELAY_TIME = 10; /** * 异步操作任务调度线程池 */ private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService"); /** * 单例模式 */ private AsyncManager() { } private static AsyncManager me = new AsyncManager(); public static AsyncManager me() { return me; } /** * 执行任务 * * @param task 任务 */ public void execute(TimerTask task) { executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS); } /** * 停止线程池 */ public void shutdown() { if (executor != null && !executor.isShutdown()) { executor.shutdown(); try { if (!executor.awaitTermination(120, TimeUnit.SECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(120, TimeUnit.SECONDS)) { log.info("Pool did not terminate"); } } } catch (InterruptedException ie) { executor.shutdownNow(); Thread.currentThread().interrupt(); } } } }
使用 demo
@GetMapping(value = "/indexttest") public String index(){ /** * 异步任务处理 */ AsyncManager.me().execute(new TimerTask() { @Override public void run() { System.out.println("我执行了异步任务"); } }); return "success"; }
也可以单独任务罗出来
AsyncFactory.java
import java.util.TimerTask;
public class AsyncFactory {
/**
* 同步任务
*/
public static TimerTask syncJob() {
return new TimerTask() {
@Override
public void run() {
System.out.println("我在调用同步");
}
};
}
}
要加个处理 退出销毁
@PreDestroy public void destroy() { try { log.info("====关闭后台任务任务线程池===="); AsyncManager.me().shutdown(); } catch (Exception e) { log.error(e.getMessage(), e); } }