Spring Boot 使用@Retryable打印重试次数

8mmmxcuj  于 2024-01-06  发布在  Spring
关注(0)|答案(2)|浏览(290)

我在这样的方法上使用@Retryable:

  1. @Retryable( value = SQLException.class,
  2. maxAttempts = 5, backoff = @Backoff(delay = 100))
  3. void testMethod(String abc) throws SQLException{
  4. //some method body that could throw sql exception
  5. };

字符串
我想打印重试次数,并显示如下消息:

  1. Retry Number : 1
  2. Retry Number : 2
  3. ...
  4. Retry Number : 5


我如何才能做到这一点?

5tmbdcev

5tmbdcev1#

你可以添加下面的代码:

  1. @Retryable( value = SQLException.class,
  2. maxAttempts = 5, backoff = @Backoff(delay = 100))
  3. void testMethod(String abc) throws SQLException{
  4. log.info("Retry Number : {}",RetrySynchronizationManager.getContext().getRetryCount());
  5. };

字符串
RetrySynchronizationManager.getContext().getRetryCount()将给予流的重试计数。

agyaoht7

agyaoht72#

可以添加重试

  1. @Retryable( value = SQLException.class, maxAttempts = 5,
  2. backoff = @Backoff(delay = 100), listeners = {"retryListener"})
  3. void testMethod(String abc) throws SQLException{
  4. //some method body that could throw sql exception
  5. };

字符串
重试计数应该像下面这样,你可以打印重试计数错误。

  1. @Slf4j
  2. @Component
  3. class MyRetryListener implements RetryListener {
  4. // Called after the final attempt (succesful or not).
  5. @Override
  6. public <T, E extends Throwable> void close(RetryContext context,
  7. RetryCallback<T, E> callback, Throwable throwable) {
  8. log.debug("Retry closing..");
  9. super.close(context, callback, throwable);
  10. }
  11. // Called after every unsuccessful attempt at a retry
  12. @Override
  13. public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
  14. log.error("Exception Occurred, Retry Count {} ", context.getRetryCount());
  15. super.onError(context, callback, throwable);
  16. }
  17. // Called before the first attempt in a retry
  18. @Override
  19. public <T, E extends Throwable> boolean open(RetryContext context,
  20. RetryCallback<T, E> callback) {
  21. log.debug("Retry opening..");
  22. return super.open(context, callback);
  23. }
  24. }

展开查看全部

相关问题