1.在Application启动类上加@EnableAsync注解
@SpringBootApplication
@EnableAsync
public class SelectionApplication {
public static void main(String[] args) {
SpringApplication.run(SelectionApplication.class, args);
}
}
2.在要执行的异步代码块上加@Async注解
@Async
public void excudeThread(ReportRequest request, IndustryExplore industryExplore) {
//业务代码
}
3.注意,要想实现任务的异步调用,同类中方法调方法是实现不了的,请看错误示例
@Service
public class IndustryServiceImpl implements IndustryService {
@Override
@Transactional(rollbackFor = Exception.class)
public void sendReport(ReportRequest request) throws InterruptedException {
executeThread(request, industryExplore);
}
@Async
public void executeThread(ReportRequest request, IndustryExplore industryExplore) {
//业务代码
}
}
想要异步调用executeThread的方法,需要将它写在另一个类中再进行调用,请看正确代码
@Service
public class IndustryServiceImpl implements IndustryService {
@Autowired
IndustryServiceAsyncImpl industryServiceAsync;
@Override
@Transactional(rollbackFor = Exception.class)
public void sendReport(ReportRequest request) throws InterruptedException {
industryServiceAsync.executeThread(request, industryExplore);
}
}
@Service
public class IndustryServiceAsyncImpl {
@Async
public void executeThread(ReportRequest request, IndustryExplore industryExplore) {
//业务代码
}
}