首页 > 解决方案 > ThreadPoolExecutor 和 Spring Async

问题描述

最初,我使用“实现”方法使用常规 java 多线程。但是,@Autowired 在 Spring 中创建类时不起作用new,因此我试图将其更改为使用 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("---------------------");
        }
    }

}

异步类

@Component
@EnableAsync
public class CountyScraper {
    volatile private String stateLink;

    @Autowired
    StateScrapeQueueRepository stateScrapeQueueRepository;

    @Autowired
    CountyScrapeRepository countyScrapeRepository;

    public CountyScraper() {
    }

    public CountyScraper(String stateLink) {
        this.stateLink = stateLink;
    }

    @Async("countyScraper")
    public void run() {
        try {
            // other code

            stateScrapeQueueRepository.updateScrapeTimestamp(stateLink);
            countyScrapeRepository.insertCountyLinks(countyLinks, website);

        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}

标签: springspring-boot

解决方案


默认情况下,Spring 使用 aSimpleAsyncTaskExecutor来执行异步方法。默认情况下,这将为每个操作生成一个新线程。

要定义您自己的执行程序以用于异步任务,请创建一个实现TaskExecutor接口的Executorbean 或名为"taskExecutor".

如果您想为此组件拥有自己的自定义执行器,您可以implement AsyncConfigurer提供自己的执行器服务:

@Override
public Executor getAsyncExecutor() {
    return MY_EXECUTOR;
}

@Override
public  AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return MY_EXCEPTION_HANDLER;
}

推荐阅读