In my spring boot application, There is one scheduler class which execute in every 30 mins and fetch around 20000 records and then insert record one by one in database and then convert that inserted record in XML and send to client. But this process takes too much time to completed 20000 records and records is increasing day by day.
So now, We have to implement asynchronous execution programming in this code so that multiple threads can perform operation instead of one by one records.
For asynchronous programming, I am trying with @Async but its not working.
Please help.
CodePudding user response:
Try putting a name, it works for me like this
@Async("ThreadPoolTaskExecutor")
In SprintBootApplication put the following
@EnableAsync
and then
@Bean("ThreadPoolTaskExecutor")
public TaskExecutor getAsyncExecutor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(100);
executor.setMaxPoolSize(200);
executor.setQueueCapacity(30);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("Async-");
executor.setTaskDecorator(new APMTaskDecorator());
return executor;
}
CodePudding user response:
If you use @Async
and @Scheduled
in same class the async methods are still executed synchronously.
@Async
generates a proxy class which encapsulated the original method. So @Async
works only if you invoke the method externally. Hence the @Scheduled
on the same class is still executed synchronously.
The simpliest solution would be to move the @Scheduled
methods to a sperate class.
@Service
public class ItemService {
@Async
public void saveAndSend() {
}
}
@Service
public class ItemSchedulerService {
private final ItemService itemService;
public ItemSchedulerService(ItemService itemService) {
this.itemService = itemService;
}
@Scheduled("...")
public void schedule() {
itemService.saveAndSend();
}
}