有时需要提交请求后可以立即返回,不需要等待业务方法执行完成才返回。
特别需要注意:@Async注解需要放在service实现方法上。
实现步骤如下:
一、在springboot启动类上添加注解@EnableAync
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import com.idreamsky.ex.bpm.func.vo.Response;
@SpringBootApplication
@EnableAsync
public class MyProjectApplication {
public static void main(String[] args) {
SpringApplication.run(MyProjectApplication.class, args);
}
}
二、添加异步配置类
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;
@Configuration
public class AsyncConfig implements AsyncConfigurer {
private Logger logger = LoggerFactory.getLogger(AsyncConfig.class);
@Bean
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 根据自己机器配置
executor.setCorePoolSize(8);
executor.setMaxPoolSize(16);
executor.setQueueCapacity(64);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("SpringAsyncThread-");
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SpringAsyncExceptionHandler();
}
// 异步调用异常处理
class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
// 通过反射获取各个初始化方法名字
String methodName = method.getName();
logger.info("Async error. methodName = {}, errorInfo = {}", methodName, throwable.toString());
}
}
}
三、在service实现方法上,加上@Async注解。
@Service
public class MyServiceImpl implements MyService {
@Async
@Override
public void testAsync() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}