Spring RestTemplate: 如何重复检查Restful API服务?

4
我正在尝试创建一个SpringBoot应用程序,该应用程序将从第三方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());
        };
    }
}

你需要仔细了解@Scheduled注解的正确使用方法。另外,CommandLineRunner仅在应用程序启动期间运行一次。你需要进一步阅读有关Spring及其用途的相关资料。 - akortex
2个回答

4

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
在您的SpringConfig类或Main类上添加@EnableScheduling注释。
您可以使用Scheduled fixedDelay或fixedRate。
@Scheduled(fixedDelay = 10000)
    public void test() {
        System.out.println("Scheduler called.");
    }

或者

@Scheduled(fixedRate  = 10000)
    public void test() {
        System.out.println("Scheduler called.");
    }

fixedDelay和fixedRate的区别:

fixedDelay - 确保任务执行完成后与下一次执行任务之间有n毫秒的延迟。

fixedRate - 每n毫秒运行一次计划任务。

理想情况下,您应该将fixedDelay或fixedRate值外部化到application.properties文件中:

@Scheduled(fixedDelayString  = "${scheduler.fixed.delay}")
    public void test() {
        System.out.println("Scheduler called.");
    }

在你的application.properties文件中添加以下配置:

scheduler.fixed.delay = 10000

希望这可以帮助到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接