How can I make spring @retryable configurable?

后端 未结 5 1721
误落风尘
误落风尘 2021-02-13 05:46

I have this piece of code

@Retryable(maxAttempts = 3, stateful = true, include = ServiceUnavailableException.class,
        exclude = URISyntaxException.class, b         


        
5条回答
  •  北恋
    北恋 (楼主)
    2021-02-13 05:59

    You can use RetryTemplate bean instead of @Retryable annotation like this:

    @Value("${retry.max-attempts}")
    private int maxAttempts;
    @Value("${retry.delay}")
    private long delay;
    
    @Bean
    public RetryTemplate retryTemplate() {
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(maxAttempts);
    
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(delay);
    
        RetryTemplate template = new RetryTemplate();
        template.setRetryPolicy(retryPolicy);
        template.setBackOffPolicy(backOffPolicy);
        return template;
    }
    

    And then use the execute method of this template:

    @Autowired
    private RetryTemplate retryTemplate;
    
    public ResponseVo doSomething(final Object data) {
        RetryCallback retryCallback = new RetryCallback() {
            @Override
            public ResponseVo doWithRetry(RetryContext context) throws SomeException {
                 // do the business
                 return responseVo;
            }
        };
        return retryTemplate.execute(retryCallback);
    }
    

提交回复
热议问题