import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; @Configuration @EnableAsync @Slf4j public class ExecutorConfig { @Bean("taskExecutor") public Executor asyncServiceExecutor() { log.info("---建立线程池---"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //核心线程数 executor.setCorePoolSize(10); //最大线程数 executor.setMaxPoolSize(20); //队列大小 executor.setQueueCapacity(200); //配置线程池中的线程的名称前缀 executor.setThreadNamePrefix("async-method-"); /* rejection-policy:当pool已经达到max size的时候,如何处理新任务 线程池对拒绝任务的处理策略:此处采用了CallerRunsPolicy策略, 当线程池没有处理能力的时候,该策略会直接在execute方法的调用线程中运行被拒绝的任务; 若是执行程序已被关闭,则会丢弃该任务 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //设置线程池关闭的时候等待全部任务都完成再继续销毁其余的Bean executor.setWaitForTasksToCompleteOnShutdown(true); //设置线程池中任务的等待时间,若是超过这个时候尚未销毁就强制销毁,以确保应用最后可以被关闭,而不是阻塞住 executor.setAwaitTerminationSeconds(60); //执行初始化 executor.initialize(); return executor; } }
/** * 异步调用测试接口 */ public interface IAsyncService { void testAsyncMethod() throws Exception; } @Service @Slf4j public class AsyncServiceImpl implements IAsyncService { //此处taskExecutor和 config中@bean保持一致 @Async("taskExecutor") @Override public void testAsyncMethod() throws Exception{ log.info("异步方法,走起---"); long start = System.currentTimeMillis(); Thread.sleep(5000); long end = System.currentTimeMillis(); log.info("异步方法,结束:" + (end - start) + "毫秒"); } }
3.测试java
public Result<?> test() { System.out.println("1====================="); System.out.println("2====================="); try { asyncService.testAsyncMethod(); } catch (Exception e) { e.printStackTrace(); } System.out.println("3====================="); System.out.println("4====================="); return Result.ok("测试成功!"); }
控制台打印以下:spring
备注:异步
若是发现启动项目报错:async
解决方案:yml中添加配置ide
spring: main: allow-bean-definition-overriding: true