【问题标题】:Methods using @Retryable and @Recover don't call @Recover method with @SpringBootTest使用@Retryable 和@Recover 的方法不使用@SpringBootTest 调用@Recover 方法
【发布时间】:2023-04-09 18:35:01
【问题描述】:

我正在使用@Retryable 方法查看SpringBoot 应用程序中的一些代码,其他方法标记为@Recover。当我们运行整个应用程序并进行我们知道会失败的远程调用时,它确实正确地调用了@Recover 方法。

但是,当我们使用 @SpringBootTest 在类似条件下运行测试时,它从不调用 @Recover 方法。我们有很多调试输出。我确实注意到我们正在运行的服务器(不是测试用例)中的一种情况,我们看到如下内容:

Exception ExhaustedRetryException: Cannot locate recovery method;

我在测试用例的调试输出中寻找它,但没有找到。

测试类有如下注解:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = { Application.class })

我们的 Application 类有以下注解:

@SpringBootApplication
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = "com")
@EnableAsync
@EnableRetry
@EnableCaching
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
        HazelcastAutoConfiguration.class, CacheAutoConfiguration.class, CassandraAutoConfiguration.class,
        CassandraDataAutoConfiguration.class, CassandraRepositoriesAutoConfiguration.class })

Spring 基础架构中是否有一些特定的方法可以让我逐步了解它为什么没有找到,或者甚至没有找到恢复方法?

更新

所以我意识到,当我在调试中执行测试时,我在堆栈跟踪中的任何地方都看不到 Spring RetryTemplate。这不是控制从 Retryable 方法到 Recover 方法的流程吗?这似乎表明我在测试类中缺少一些设置,或者可能表明这根本无法在测试类中完成(我希望这不是真的)。​​

更新

好的,我设法解决了这个问题。发生这种情况是因为我忽略了从 Spring 注入 bean,我只是手动创建了一个。这意味着它没有连接到使用 RetryTemplate,因此它根本没有尝试找到 @Recover 方法。一旦我将“@Autowired”添加到测试类中的实例变量中,它就解决了这个问题(并遇到了下一个问题,但我理解那个问题)。

【问题讨论】:

    标签: java spring spring-boot spring-retry


    【解决方案1】:

    该异常来自RecoverAnnotationRecoveryHandler,因此看起来重试是可操作的,但由于某种原因它找不到恢复方法。

    Method method = findClosestMatch(cause.getClass());
    if (method == null) {
        throw new ExhaustedRetryException("Cannot locate recovery method", cause);
    }
    

    所以,它正在寻找与异常匹配的方法。

    findClosestMatch 只是简单地扫描发现的方法以查找具有匹配参数的方法。

    我建议您使用调试器并在其中放置一个断点以找出它找不到匹配项的原因。

    【讨论】:

    • 是的,我想通了。它没有找到匹配项,因为它没有寻找匹配项,因为我是手动创建 bean,而不是从 spring 注入它,所以它不是从 RetryTemplate 执行的。我会用更多信息更新原始帖子。
    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2019-01-18
    相关资源
    最近更新 更多