java - Spring RestTemplate:如何重复检查 Restful API Service?
问题描述
我正在尝试创建一个 SpringBoot 应用程序,它将使用来自 3rd 方 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())
}
它不需要是 a Bean
,它可以是一个简单的方法。有关更多信息,请参阅 Spring 指南https://spring.io/guides/gs/scheduling-tasks/
推荐阅读
- c# - C# | 枚举排序的编译时间检查
- angular - Chart.js 和 Angular 的渐变效果
- android - Android如何让这种“波浪”像自定义设计的布局背景?
- javascript - 我的 smtp 密码包含特殊字符给出错误
- image - 图像宽高对迁移学习模型精度的影响
- android - 特定用户的 Firebase 数据库集合
- c# - EF Core ChangeTracker() 修改实体的当前值和原始值相同
- postgresql - docker compose后Postgresql连接失败
- mysql - 获取表的所有列并用 CASE 语句中的值替换一列
- authorization - 如何在 Cognito 中使用自定义权限