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

时间:2017-12-16 09:54:45

标签: java spring-retry

如何使用spring-retry注释在@Retryable()注册听众?

@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。因此,如果我有多个听众,那么我该如何让特定的听众听取我的可重试服务呢?

3 个答案:

答案 0 :(得分:1)

在弹簧重试的官方Github回购中有一个非常古老的拉取请求,这似乎可以实现你想做的事情。

https://github.com/spring-projects/spring-retry/pull/77

答案 1 :(得分:0)

我认为您正在寻找类似以下的内容。 Retryable批注具有侦听器参数(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);
    }
}

我希望这会有所帮助。

答案 2 :(得分:0)

您可以像这样在Listener中注册@Retryable。 listeners属性采用字符串数组。字符串表示侦听器类的名称。

@Retryable(maxAttempts = 5,backoff = @Backoff(delay = 5000),listeners = {"retryListener"})
public void getSomeData() {
                log.info("Get Some Date !!!!");
                throw new RuntimeException("Test Exception");
            } 


@Component
public class RetryListener extends RetryListenerSupport {

    @Override
    public <T, E extends Throwable> void close(RetryContext context,
                                               RetryCallback<T, E> callback, Throwable throwable) {

        log.error("Unable to recover from  Exception");
        log.error("Error ", throwable);
        super.close(context, callback, throwable);
    }

    @Override
    public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        log.error("Exception Occurred, Retry Count {} ", context.getRetryCount());
        super.onError(context, callback, throwable);
    }

    @Override
    public <T, E extends Throwable> boolean open(RetryContext context,
                                                 RetryCallback<T, E> callback) {
        log.error("Exception Occurred, Retry Session Started ");
        return super.open(context, callback);
    }
}
相关问题