总结:异步任务怎样快速实现呢 当然可以自己搞个线程池然后submit,spring4 里面提供一个注解 @Async 默认是 一个可缓存的线程池,最好是还是自己定义一个线程池大小,注意用注解 必须是能代理的,不然不会生效。
使用如下:开启异步 注意了:必须对象必须是能被代理的 不然重试 和 异步 都不会生效
1.开启注解
@SpringBootApplication
@EnableSwagger2
@EnableRetry //开启重试机制
@EnableAsync //开启异步
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.定义线程池
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(threadNamePrefix);
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Bean("taskExecutor1")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("MyExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
3.使用
@Async("taskExecutor")
public void sendSms() throws InterruptedException {
log.info("开始做任务2:发送短信");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务1,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor1")
public void send() throws InterruptedException {
log.info("hello:发送短信");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("hello:" + (end - start) + "毫秒");
}
4.测试
private @Autowired
AsyncTask asyncTask;
@Test
public void test() throws InterruptedException {
asyncTask.sendSms();
// asyncTask.send();
Thread.sleep(100000);
}