处理前需要等待的Java rest api [英] Java rest api that needs to wait before processing

查看:42
本文介绍了处理前需要等待的Java rest api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java rest API,物联网设备将使用它来发送数据.每个设备都有一个时间段(比如 15 秒)来与 API 通信.在该时间段内,可能有多个消息具有相同的数据集.

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.

我想要做的是,当 API 收到来自设备的新消息时,它会等到时间段结束并收集收到的消息.并且仅在时间段结束时处理消息.

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?

谢谢.

编辑使用弹簧靴.

推荐答案

您应该尝试使用异步端点来调用同步 REST.您可以定义达到超时后要执行的操作.

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

例如,在 Spring Boot 中,您可以返回 Callable 并使用 TaskExecutor:

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);

    }
}

您可能需要在 Spring 中为 Task Executor 线程池添加一些配置:

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);
            }
        };
    }

}

这里有更多的阅读:

这篇关于处理前需要等待的Java rest api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆