[英]How to get details of Spring Boot @Async method's rejected task?
在我的應用程序中,我使用@Async
方法調用 rest 服務並基於 rest 服務結果,我正在更新數據庫中的 MyJob 狀態。
@Async("thatOneTaskExecutor")
public void myAsyncTask(MyJob job) {
// get job details from the job and call rest service
// update the job with the result from rest service and save updated MyJob to DB
}
我正在使用 Spring 的ThreadPoolTaskExucutor
Exucutor ,下面是我的AsyncConfiguration
class 的快照,我在其中聲明了這個任務執行器。
private ThreadPoolTaskExecutor createExecutor(String name, int core, int max, int queue) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(core);
executor.setMaxPoolSize(max);
executor.setQueueCapacity(queue);
executor.setThreadNamePrefix(name);
executor.setTaskDecorator(new MdcAwareTaskDecorator());
executor.initialize();
return executor;
}
@Bean(name = "thatOneTaskExecutor")
public Executor taskExecutor() {
String prefix = "thatOneTask-";
String corePoolSize = 12;
String maxPoolSize = 20;
String queueSize = 1000;
ThreadPoolTaskExecutor executor = createExecutor(prefix, corePoolSize, maxPoolSize, queueSize);
executor.setRejectedExecutionHandler(new RejectedExecutionHandlerImpl());
return executor;
}
如您所見,我為我的 Executor 配置了RejectedExecutionHandler
。 根據 Spring 文檔,當隊列已滿時,將調用此方法。
* Method that may be invoked by a {@link ThreadPoolExecutor} when * {@link ThreadPoolExecutor#execute execute} cannot accept a * task. This may occur when no more threads or queue slots are * available because their bounds would be exceeded, or upon * shutdown of the Executor.
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
log.error("Task Rejected because of max queue size");
// How to get info about that particular job, for which Task executor rejected this task??
}
}
被拒絕的執行處理程序對我來說工作正常,現在在這個rejectedExecutorion
的Executorion 方法中,我想訪問異步任務被拒絕的MyJob (我的異步方法的參數)。 我想用狀態更新那個特定的被拒絕的工作,以便我以后可以運行玉米並處理那些被拒絕的工作。 在這個rejectedExecution
方法中,我只有Runnable
和ThreadPoolExucutor
,我如何在這里提取/獲取有關 MyJob 的信息?
我的應用程序的 Spring 啟動版本是2.2.2.RELEASE
您可以考慮通過為MyJob
Class 實現Runnable
接口直接使用TaskExecutor
而不是@Async
注釋,並在run()
方法中執行所需的異步操作。
Runnable r
可以在處理程序的rejectedExecution
方法中被轉換回MyJob
Object ,因此您可以從那里檢索您的工作信息。
public class Myjob implements Runnable{
.......
@Override
public void run(){
//get job details from the job and call rest service
//update the job with the result from rest service and save updated MyJob to DB
}
}
@Autowired
TaskExecutor taskExecutor;
public void myAsyncTask(MyJob job) {
taskExecutor.execute(job)
}
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
log.error("Task Rejected because of max queue size");
if(r.getClass()==MyJob.class)
{
MyJob failedJob=(MyJob)r; //Job info
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.