@Retryable多次调用,即使没有异常发生

时间:2019-07-04 19:22:03

标签: java resttemplate spring-retry

如果使用@Retryable调用另一个服务时出现任何问题,我已经使用spring RestTemplate来实现重试功能调用。

该函数在下面给出,问题是我将maxAttempts设置为4,以防万一发生任何异常,应尝试4次。但是,即使没有任何例外,该函数也会执行4次,并且会在数据库中创建4个雇员条目。

createEmployee函数,该函数调用另一个服务以在数据库中创建员工

@Retryable(value = { Exception.class }, maxAttempts = 4, backoff = @Backoff(delay = 1000))
public Response createEmployee(EmployeeRequest employeeRequest) 
{
  log.info(“creating employee”)
  :
  // calls another micro service using RestTemplate which creates employee into the DB
  :
}

@EnableRetry在AppConfig中

@Configuration
@EnableRetry
public class AppConfig {
}

有人可以帮我吗

3 个答案:

答案 0 :(得分:0)

您应该查看“调用另一个微服务”的实现。

该逻辑内部可能正在调用另一个服务引发异常。我建议创建一个自定义异常,并将其用于您的Retry定义。然后,您可以检查是否有另一种意外异常是强制重试4次的异常。

@Retryable(value = { YourCustomException.class }, maxAttempts = 4, backoff = @Backoff(delay = 1000))
public Response createEmployee(EmployeeRequest employeeRequest) 
{
  log.info(“creating employee”)
  :
  // calls another micro service using RestTemplate which creates employee into the DB
  :
}

答案 1 :(得分:0)

检查您的服务在失败之前所花费的最长时间是多少,请根据此时间设置退避时间。 检查resttemplate在失败的情况下会引发什么异常,仅将其标记为重试。

答案 2 :(得分:0)

好,检查在失败的情况下resttemplate可能引发什么异常,将它们标记为重试。