Изначально я использовал обычную многопоточность Java, используя метод «Implements». Однако @Autowired не работает, когда класс создается с new
в Spring, поэтому я пытаюсь изменить его на использование метода 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();
}
}
}