Skip to content
Advertisement

Send an response 200 from a Spring boot controller for asyncronus processing

I have a scenario: I’ve a controller. My controller is calling the service class.Service class will fetch all the records from data base and post it to kafka.But I don’t want my client who is calling the api to wait till the entire data is posted to kafka. I want it to do in a asynchronous way. Client’s work is only to invoke the api that’s all. We will immediately send 200 response code.

In back end the data fetching from DB and processing to kafka will happen. Can you please suggest how this can be done.

public class SampleController {

    private  SampleService sampleService;
        @PostMapping("/")
        public String handleAsyncResponse(@RequestBody Requestbean bean) {
        sampleService.posttokafka(bean);
    }
}

Thanks

Advertisement

Answer

You can achieve it via @Async way as follows, first define a bean:

@Configuration
public class SThreads {
    @Bean
    public TaskExecutor concurrentTasks() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix("default_task_executor_thread");
        executor.initialize();
        return executor;
    }
}

And the annotate the task with @Async("concurrentTasks")

@Async("concurrentTasks")
public static void myAsyncTask() throws ExecutionException, InterruptedException {
    ....
}

Then you can call the myAsyncTask and it will not block the caller.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement