java - 将监听器注册到 spring 的 @Retryable 的注解方式

标签 java spring-retry

如何使用@Retryable()注解在spring-retry中注册监听器?

@Bean
public RetryListener myRetryListener() {
    return new MyRetryListener();
}

@Service
public class SampleService {
   private int cnt = 1;

   @Retryable(RuntimeException.class)
   public void retryMethod(int x) throws Exception {
      System.out.println("SampleService invoked.");
      Thread.sleep(500);

      if (cnt++ < 4) {
        throw new RuntimeException("SampleService throwing exception");
      }
   }

}

如果我创建任何监听器 bean,它会自动注册到 RetryTemplate。因此,如果我有多个监听器,那么如何让特定的监听器监听我的可重试服务?

最佳答案

我认为您正在寻找如下内容。 Retryable注解有listeners参数(spring-retry:1.2.4.RELEASE)

@Retryable(value = { Exception.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000), listeners = "networkcallRetryLogListener")
List<ServiceObj> getDataFromThirdpartyService();

networkcallRetryLogListener 尝试登录我的案例。

public class NetworkcallRetryLogListener extends RetryListenerSupport {
private static final Logger LOG = LoggerFactory.getLogger(NetworkcallRetryLogListener.class);

@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
    LOG.warn("Retry attempt {} for retryable method {} threw exception {}", context.getRetryCount(),
            context.getAttribute("context.name"), ExceptionUtils.getStackTrace(throwable));
    super.onError(context, callback, throwable);
    }
}

希望对您有所帮助。

关于java - 将监听器注册到 spring 的 @Retryable 的注解方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47844432/

相关文章:

java - 如何使用椭圆验证框架验证数组?

java - 向现有 Java 应用程序添加 Web 界面 (Spring MVC)

spring - 在用@Async 注释的方法中调用@Retryable 方法不起作用

Spring Retry 与 Hystrix

java - 如何使用字符串数组填充枚举友好字符串

java - 如何在Android 9上使Apps支持

java - org.hibernate.exception.GenericJDBCException : could not execute query] with root cause

apache-kafka - 当目标系统关闭时,停止 Spring Cloud Stream @StreamListener 监听

Spring-retry - @Circuitbreaker 没有重试

java - 如何在 SpringBootTest 中模拟 Spring 的 @Retryable 属性,例如 maxAttemps 和延迟