【问题标题】:ThreadPoolExecutor and Spring AsyncThreadPoolExecutor 和 Spring Async
【发布时间】:2019-06-03 22:04:27
【问题描述】:

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

【问题讨论】:

    标签: spring spring-boot


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我会在哪个课上做implement AsyncConfigurerScheduledCountyScraperCountyScraper 类?
    • 开启CountryScraper,因为它有@Async 方法。
    • 我有点困惑。我们如何实际将 stateLink 传递给 public CountyScraper(String stateLink) { ... }
    • 我现在明白了。我必须自动装配课程
    • 我做的有点不一样,你能看看这个问题吗? stackoverflow.com/questions/56437029/…
    猜你喜欢
    • 2011-11-11
    • 2023-03-10
    • 2011-09-12
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    相关资源
    最近更新 更多