首页 > 解决方案 > 如何在 Spring Boot 中查询 Db 几秒钟直到得到结果

问题描述

我想调用repository.findbyId(id)直到在特定秒内得到结果。

例如:选择员工详细信息,其中 id =1 连续 25 秒。如果我们在第 15 秒得到结果,我们必须停止调用。

我尝试使用@Retryable,但它不适合我的情况。

我们可以通过Awaitility.await().atMost(20, TimeUnit.SECONDS).pollInterval(50, TimeUnit.MILLISECONDS) .untilAsserted()}来实现这一点

但是,我们只能使用 Awaitility 来测试断言。Spring Boot 中是否有其他可用选项代替 Awaitility?

标签: javaspringspring-bootcassandraspring-data-jpa

解决方案


spring-retry应该有你需要的一切。即使基于注解的 API with@Retryable不合适,spring-retry 也有程序化重试RetryTemplatehttps://www.baeldung.com/spring-retry#retrytemplate),其中可以配置每个细节。

您也可以自己编写重试机制。根据您的描述,您只需要一个循环Thread.sleep()和一些计时器/计数器。Awaitility 和 spring-retry 也只是使用Thread.sleep(),但它看起来要复杂得多,因为它们的可配置性很高(您不需要)。


推荐阅读