ThreadPoolExecutor和Spring异步
最初,我使用“implements”方法使用常规java多线程。但是,在Spring中使用ThreadPoolExecutor和Spring异步,spring,spring-boot,Spring,Spring Boot,最初,我使用“implements”方法使用常规java多线程。但是,在Spring中使用new创建类时,@Autowired不起作用,因此我尝试将其更改为使用Spring的Async方法。这就是我目前所拥有的。如何将线程添加到ThreadPoolExecutor 应该创建线程的类 @Component public class ScheduledCountyScraper { @Autowired StateScrapeQueueRepository stateScrapeQ
new
创建类时,@Autowired不起作用,因此我尝试将其更改为使用Spring的Async
方法。这就是我目前所拥有的。如何将线程添加到ThreadPoolExecutor
应该创建线程的类
@Component
public class ScheduledCountyScraper {
@Autowired
StateScrapeQueueRepository stateScrapeQueueRepository;
@Autowired
CountyScrapeRepository countyScrapeRepository;
// @Scheduled(cron = "0 0 */3 * * *")
@EventListener(ApplicationReadyEvent.class)
public void scrapeCountyLinks() {
System.out.println("Scrape county links ran!");
try {
List<String> stateLinks = stateScrapeQueueRepository.getStatesLinks(website);
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
//what to do here?
executor.shutdown();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("---------------------");
}
}
}
默认情况下,Spring使用
SimpleAsyncTaskExecutor
来执行异步方法。默认情况下,这将为每个操作生成一个新线程
要定义用于异步任务的自己的执行器,请创建一个实现TaskExecutor
接口的bean或一个名为“TaskExecutor”
的executor
bean
如果您想为该组件拥有自己的自定义执行器,您可以实现AsyncConfigurer
并提供自己的执行器服务:
@Override
public Executor getAsyncExecutor() {
return MY_EXECUTOR;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return MY_EXCEPTION_HANDLER;
}
我会在哪个类上实现AsyncConfigurer?
CountryScraper
上的ScheduledCountyScraper
或CountyScraper
类?因为它有@Async
方法。我有点困惑。我们如何将stateLink传递给公共CountyScraper(stringstatelink){…}?我现在明白了。我必须自动连线classI做的有点不同,你能看看这个问题吗?
@Override
public Executor getAsyncExecutor() {
return MY_EXECUTOR;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return MY_EXCEPTION_HANDLER;
}