SpringBoot中使用@Async注解标记的方法,会在调用方法的当前线程之外的独立线程中执行。
Spring使用@Async注解实现异步任务:
- application类上加@EnableAsync注解:
@EnableAsync
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
- application同级目录下添加配置类(也可不配,方法上直接加@Async注解即可):
package com.h3c.core;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步任务线程池配置类
*
* @Description: 异步任务线程池配置类
*/
@Configuration
public class TaskPoolConfig {
@Bean("testTaskExecutor")
public Executor testTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("testTaskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
- 需要异步的方法或类上添加@Async注解:
@Async("testTaskExecutor")
public void testAsync(){
return;
}
注:异步方法和主方法不能在同一个service下,否则还会同步执行