Java 如何调用一个新的@Async方法,但等待一个条件?
我有一个Spring启动应用程序,它实现了一个AMQP MessageListener。此侦听器调用由池大小为的ThreadPoolTaskExecutor管理的@Async方法。当有许多传入消息时会出现问题,因此这些消息会丢失,因为没有可用的异步工作进程 我使用的是SpringCore5.0.7-RELEASE,Java8 这是我的代码: 异步配置程序:Java 如何调用一个新的@Async方法,但等待一个条件?,java,multithreading,spring-boot,asynchronous,Java,Multithreading,Spring Boot,Asynchronous,我有一个Spring启动应用程序,它实现了一个AMQP MessageListener。此侦听器调用由池大小为的ThreadPoolTaskExecutor管理的@Async方法。当有许多传入消息时会出现问题,因此这些消息会丢失,因为没有可用的异步工作进程 我使用的是SpringCore5.0.7-RELEASE,Java8 这是我的代码: 异步配置程序: @EnableAsync @Configuration public class AsyncConfiguration extends As
@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):
我的消息侦听器:
...
@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()
检查当前队列大小,以验证消息是否确实丢失或只是卡在队列中。谢谢。但我无法解决我的问题。最后,由于时间的原因,我让这个任务处于待机状态。
...
@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 );
}
}