我使用的是Feign客户端,
我有定位服务。因此,我使用FeignClient为我的LocationService创建了一个客户端。
@FeignClient(url="http://localhost:9003/location/v1", name="location-service")
public interface LocationControllerVOneClient {
@RequestMapping(value = "/getMultipleLocalities", method = RequestMethod.POST)
public Response<Map<Integer, Locality>> getMultipleLocalities(List<Integer> localityIds);
@RequestMapping(value = "/getMultipleCities", method = RequestMethod.POST)
public Response<Map<Integer, City>> getMultipleCities(List<Integer> cityIds);
@RequestMapping(value = "/getMultipleStates", method = RequestMethod.POST)
public Response<Map<Integer, State>> getMultipleStates(List<Integer> stateIds);
@RequestMapping(value = "/getMultipleCitiesName", method = RequestMethod.POST)
public Response<Map<Integer, String>> getMultipleCitiesName(MultiValueMap<String, String> formParams);
@RequestMapping(value = "/getMultipleStatesName", method = RequestMethod.POST)
public Response<Map<Integer, String>> getMultipleStatesName(MultiValueMap<String, String> formParams);
@RequestMapping(value = "/getMultipleLocalitiesName", method = RequestMethod.POST)
public Response<Map<Integer, String>> getMultipleLocalitiesName(MultiValueMap<String, String> formParams);
}
现在,其他服务可能会通过LocationClient调用此LocationService。
我想在一个公共的地方为这个Feign客户端(LocationClient)做异常处理(即,我不希望每个调用方都这样做。这应该是LocationClient的一部分)。异常可能是连接被拒绝(如果LocationService关闭)、超时等。
您可以使用一个外部ErrorDecoder来处理异常。以下是供您参考的网址。
https://github.com/OpenFeign/feign/wiki/Custom-error-handling
示例:
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 MyBadRequestException();
}
return defaultErrorDecoder.decode(methodKey, response);
}
}
要获得这个ErrorDecoder,你需要为它创建一个bean,如下所示:
@Bean
public MyErrorDecoder myErrorDecoder() {
return new MyErrorDecoder();
}
您可以定义一个回退客户端,当出现异常(如超时或连接被拒绝)时调用该客户端:
@FeignClient(url="http://localhost:9003/location/v1", name="location-service", fallback=LocationFallbackClient.class)
public interface LocationControllerVOneClient {
...
}
LocationFallbackClient
必须实现LocationControllerVOneClient
。