我已经创建了服务'A',它需要由服务'B‘使用伪客户端调用,如果服务'A’由于某些验证而失败,那么服务'A‘返回包含以下细节的错误响应,(1)http状态代码(2)错误消息(3)自定义错误映射,其中包含自定义错误代码及其错误消息,例如<"Emp-1001",“无效员工Id">。
来自服务'B‘的我们使用伪解码器来处理假异常,但它只提供http状态代码,而不是自定义错误代码。
而且,在我的例子中,对于不同的场景,http状态代码是相同的,但是自定义错误映射值是不同的。在两者结合(http状态代码+自定义错误映射)时,我们必须处理服务'B‘中的异常。
请对此提供一些建议
发布于 2021-02-16 21:00:06
您可以启用断路器,还可以根据返回的错误将应用程序配置为应用不同的回退方法,请执行以下步骤:
1.-开启断路器本身
@SpringBootApplication
@EnableFeignClients("com.perritotutorials.feign.client")
@EnableCircuitBreaker
public class FeignDemoClientApplication {2.-创建备份bean
@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PetAdoptionClientFallbackBean implements PetAdoptionClient {
@Setter
private Throwable cause;
@Override
public void savePet(@RequestBody Map<String, ?> pet) {
log.error("You are on fallback interface!!! - ERROR: {}", cause);
}
}在回退实现时,您必须记住一些事情:
3.-您的ErrorDecoder,根据返回的HTTP错误实现回退启动:
public class MyErrorDecoder implements ErrorDecoder {
private final ErrorDecoder defaultErrorDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() >= 400 && response.status() <= 499) {
return new MyCustomBadRequestException();
}
if (response.status() >= 500) {
return new RetryableException();
}
return defaultErrorDecoder.decode(methodKey, response);
}
}4.-在配置类中,将Retryer和ErrorDecoder添加到Spring上下文中:
@Bean
public MyErrorDecoder myErrorDecoder() {
return new MyErrorDecoder();
}
@Bean
public Retryer retryer() {
return new Retryer.Default();
}还可以向Retryer添加自定义:
class CustomRetryer implements Retryer {
private final int maxAttempts;
private final long backoff;
int attempt;
public CustomRetryer() {
this(2000, 5); //5 times, each 2 seconds
}
public CustomRetryer(long backoff, int maxAttempts) {
this.backoff = backoff;
this.maxAttempts = maxAttempts;
this.attempt = 1;
}
public void continueOrPropagate(RetryableException e) {
if (attempt++ >= maxAttempts) {
throw e;
}
try {
Thread.sleep(backoff);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
@Override
public Retryer clone() {
return new CustomRetryer(backoff, maxAttempts);
}
}如果您想获得一个关于如何在应用程序中实现假冒伪劣的功能示例,请阅读这文章。
https://stackoverflow.com/questions/59942822
复制相似问题