mumbo_s5
mumbo_s5

Reputation: 171

Java rest api that needs to wait before processing

I have a Java rest API which will be used by IOT devices to send data. Each device has a time period (say 15 seconds) to communicate with the API. Within that time period there can be more than one message with the same set of data.

What I want to do is, when the API receive a new message from a device, it wait till the end of the time period and collect the messages received. And process the messages only when the time period is over.

What should I use to collect and process messages for a given time period?

Thanks.

EDIT Using spring boot.

Upvotes: 2

Views: 2181

Answers (1)

Sebastian D'Agostino
Sebastian D'Agostino

Reputation: 1675

You should try using an asyncronous endpoint to call to a syncronous REST. You can define what to do after a timeout is reached.

For example, in Spring Boot you could return a Callable and use a TaskExecutor:

@Controller
public class MyController {

    @RequestMapping("/endpoint") 
    public @ResponseBody WebAsyncTask<String> handleRequest (HttpServletRequest request) {

        Callable<String> callable = () -> {
            return "Callable";
        };

        ConcurrentTaskExecutor taskExecutor = new ConcurrentTaskExecutor(Executors.newFixedThreadPool(1));

        return new WebAsyncTask<>(15000L, taskExecutor, callable);

    }
}

You will probably need to add some configuration in Spring for the Task Executor Thread Pool:

@SpringBootApplication
public class AsyncConfigExample {

    @Bean
    WebMvcConfigurer configurer(){
        return new WebMvcConfigurerAdapter(){
            @Override
            public void configureAsyncSupport (AsyncSupportConfigurer configurer) {
                ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
                t.setCorePoolSize(10);
                t.setMaxPoolSize(100);
                t.setQueueCapacity(50);
                t.setAllowCoreThreadTimeOut(true);
                t.setKeepAliveSeconds(120);
                t.initialize();
                configurer.setTaskExecutor(t);
            }
        };
    }

}

Here is more to read:

Upvotes: 1

Related Questions