我正在尝试创建一个SpringBoot应用程序,该应用程序将使用来自第三方REST API的数据,并根据对该数据的事件/更改将Websocket通知推送给我自己的客户端。我消耗的数据经常变化,有时每秒变化数十次(加密货币价格波动的行为与此数据相似)。我想以固定的间隔(例如,每1-10秒)重复调用API,监视某些事件/更改,并在发生这些事件时触发Websocket推送。
通过遵循以下指南,我已经能够构建一个简单的Spring Boot应用程序来推送Websocket通知并使用API:
问题:我只能让应用程序<一次>从请求来自API的数据。我已经花了数小时来搜索我能想到的“ Spring RestTemplate多个/重复/持久调用”的每个变体,但是找不到适合我特定用途的解决方案。我发现的最接近的示例使用重试,但即使最终也会放弃。我希望我的应用程序继续请求此数据,直到我关闭该应用程序为止。我知道我可以将其包装在while(true)
语句或类似的语句中,但这对于SpringBoot这样的框架似乎并不正确,并且在尝试实例化RestTemplate时仍然存在问题。
如何实现对RESTful API资源的持久查询?
下面是我的Application类中的内容
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());
};
}
}
答案 0 :(得分:1)
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/
答案 1 :(得分:0)
在您的SpringConfig类或Main类上添加@EnableScheduling
注释。
您可以使用Scheduled fixedDelay或fixedRate
@Scheduled(fixedDelay = 10000)
public void test() {
System.out.println("Scheduler called.");
}
OR
@Scheduled(fixedRate = 10000)
public void test() {
System.out.println("Scheduler called.");
}
fixedDelay和fixedRate之间的区别:
fixedDelay -确保在执行任务的完成时间和下一次执行任务的开始时间之间有n毫秒的延迟。
fixedRate -每n毫秒运行一次计划任务。
理想情况下,您还应该在application.properties文件中外部化fixedDelay或fixedRate值:
@Scheduled(fixedDelayString = "${scheduler.fixed.delay}")
public void test() {
System.out.println("Scheduler called.");
}
在application.properties文件中,添加以下配置:
scheduler.fixed.delay = 10000
希望这会有所帮助。