我正在尝试创建一个 SpringBoot 应用程序,该应用程序将使用来自第 3 方 REST API 的数据,并根据该数据的事件/更改将 Websocket 通知推送到我自己的客户端。我正在消耗的数据经常变化,有时每秒几十次(加密货币价格波动的行为与此数据类似)。我想以固定的时间间隔(例如每 1-10 秒)重复调用 API,监视某些事件/更改并在这些事件发生时触发 Websocket 推送。
我已经能够构建一个简单的 Spring Boot 应用程序,该应用程序可以按照以下指南推送 Websocket 通知并使用 API:
问题:我只能让应用程序从 API 请求数据一次。我花了几个小时搜索我能想到的“Spring RestTemplate 多次/重复/持久调用”的每个变体,但我找不到解决我的特定用途的解决方案。我发现的最接近的例子使用重试,但即使是那些最终也会放弃。我希望我的应用程序不断请求这些数据,直到我关闭该应用程序。我知道我可以将它包装在 while(true) 语句或类似的东西中,但这对于像 SpringBoot 这样的框架来说似乎确实不合适,并且在尝试实例化 RestTemplate 时仍然存在问题。
如何实现 RESTful API 资源的持久查询?
下面是我的应用程序类中的内容
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableScheduling
public class Application {
private static final String API_URL = "http://hostname.com/api/v1/endpoint";
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Response response= restTemplate.getForObject(API_URL, Response.class);
System.out.println(response.toString());
};
}
}
最佳答案
CommandLineRunner
每次应用程序启动时仅运行一次。相反,您希望使用 @Scheduled
注释以固定时间间隔执行重复操作,例如
@Scheduled(fixedDelay = 1000L)
public void checkApi() {
Response response = restTemplate.getForObject(API_URL, Response.class);
System.out.println(response.toString())
}
它不需要是一个Bean
,它可以只是一个简单的方法。有关更多信息,请参阅 Spring 指南 https://spring.io/guides/gs/scheduling-tasks/
关于java - Spring RestTemplate : How to repeatedly check Restful API Service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149660/