[英]How can I invoke a new @Async method but wait a condition?
我有一個實現 AMQP MessageListener 的 Spring Boot 應用程序。 此偵聽器調用由具有池大小的 ThreadPoolTaskExecutor 管理的 @Async 方法。 當有很多傳入消息時會出現問題,因此這些消息會丟失,因為沒有可用的異步工作程序。
我使用的是 Spring Core 5.0.7-RELEASE, Java 8
這是我的代碼:
異步配置器:
@EnableAsync
@Configuration
public class AsyncConfiguration extends AsyncConfigurerSupport {
@Override
@Bean("docThreadPoolTaskExecutor")
public Executor getAsyncExecutor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(8);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("DocWorkerThread-");
executor.initialize();
return executor;
}
我的后台服務( MyAsyncService ):
@Async("docThreadPoolTaskExecutor")
@Override
public void generaDocumento(String idUser, int year) {
//... some heavy and slow process
}
我的消息偵聽器:
...
@Autowired
private MyAsyncService myAsyncService;
@Override
@EntryPoint
public void onMessage(Message message) {
try {
final String mensaje = new String(message.getBody(), StandardCharsets.UTF_8);
final MyPojo payload = JsonUtils.readFromJson(mensaje , MyPojo.class);
myAsyncService.generaDocumento(payload.getIdUser(), Integer.valueOf(payload.getYear()));
} catch ( Throwable t ) {
throw new AmqpRejectAndDontRequeueException( t );
}
}
我需要有人給我一些想法來解決這個問題。
ThreadPoolTaskExecutor
默認有一個隊列。 當您達到corePoolSize
時,應將消息添加到隊列中。 當隊列已滿時,將啟動更多工作人員,直到達到maxPoolSize
。 您可以通過executor.getThreadPoolExecutor().getQueue().size()
檢查當前隊列大小,以驗證消息是否真的丟失或只是卡在隊列中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.