spring - 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();
}
}
}
解决方案
默认情况下,Spring 使用 aSimpleAsyncTaskExecutor
来执行异步方法。默认情况下,这将为每个操作生成一个新线程。
要定义您自己的执行程序以用于异步任务,请创建一个实现TaskExecutor
接口的Executor
bean 或名为"taskExecutor"
.
如果您想为此组件拥有自己的自定义执行器,您可以implement AsyncConfigurer
提供自己的执行器服务:
@Override
public Executor getAsyncExecutor() {
return MY_EXECUTOR;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return MY_EXCEPTION_HANDLER;
}
推荐阅读
- ruby-on-rails - Rails 渲染格式 haml
- php - 如何在多维数组中调用关联数组键?
- oracle - 使用序列构建 Oracle 视图
- css - 正文中断布局上的等宽字体
- java - 使用 Java 和 Python 的 uuencoded 文件之间的区别
- sql-server - 如何根据 json 中的 id 从表中删除行
- php - 使用 PHP SoapClient 将多个值发送到同一个字段
- python - AttributeError:模块“pydotplus”没有属性“节点”
- python - 未定义字符的 Unicode 编码错误
- django - Django - 空表单无法保存在数据库中