简体   繁体   English

如何在 Spring Boot 中持续接收和解析来自 REST API 的 JSON

[英]How to continuously receive and parse the JSON from REST API in spring boot

There is a remote server keep bringing about the data in JSON format.有一个远程服务器不断带来 JSON 格式的数据。 Here is a REST API named http://192.168.1.101:8000/v1/status ,and if I want to collect the data continuously in Spring Boot.Here is a possible JSON from the REST API:这是一个名为http://192.168.1.101:8000/v1/status的 REST API,如果我想在 Spring Boot 中连续收集数据。这是来自 REST API 的一个可能的 JSON:

{
"run-status": 0,
"opr-mode": 0, 
"ready": false, 
"not-ready-reason": 1, 
"alarms":["ps", "prm-switch"] 
}

I want to keep collecting or just subscribe the REST API, if there is a JSON and then collect it.我想继续收集或只是订阅 REST API,如果有一个 JSON 然后收集它。

There are two main approaches of achieving what you are looking for:有两种主要方法可以实现您的目标:

  1. Polling - If this service already exists and you do not have control over the code, then this might be your only option.轮询 - 如果此服务已经存在并且您无法控制代码,那么这可能是您唯一的选择。 You constantly poll the given URL to check if data has been changed.您不断轮询给定的 URL 以检查数据是否已更改。

    In spring, you can use @Scheduled annotation to execute and poll at any given frequency (using cron expression or fixed delays).在 spring 中,您可以使用@Scheduled注释以任何给定频率执行和轮询(使用 cron 表达式或固定延迟)。

    https://www.baeldung.com/spring-scheduled-tasks - provides a detail of how to create a scheduled tasks. https://www.baeldung.com/spring-scheduled-tasks - 提供了如何创建计划任务的详细信息。

  2. Webhooks - If you have control over your server code, you can use webhooks to notify subscriber about availability of data. Webhooks - 如果您可以控制服务器代码,则可以使用 Webhooks 通知订阅者有关数据的可用性。 It is a callback mechanism where caller will receive a notification about data changes on the server, and subscriber can then call server to fetch data immediately.这是一种回调机制,调用者将收到有关服务器上数据更改的通知,然后订阅者可以立即调用服务器获取数据。

More about Polling and Webhooks can be found on this URL: https://dzone.com/articles/webhooks-vs-polling-youre-better-than-this-1有关轮询和 Webhooks 的更多信息,请访问此 URL: https ://dzone.com/articles/webhooks-vs-polling-youre-better-than-this-1

Make a "while" cycle what calls your function then goes to sleep (if needed) for the time you want.做一个“while”循环,调用您的函数,然后在您想要的时间内进入睡眠状态(如果需要)。

Or just while (true) {}或者就在 (true) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM