代码语言:javascript复制
@Slf4j
@Configuration(proxyBeanMethods = false)
public class FeignLoadBalancedConfiguration {
@Bean
public LoadBalancerFeignClient feignClient(CachingSpringLoadBalancerFactory cachingFactory,
SpringClientFactory clientFactory) {
return new LoadBalancerFeignClient(new Client.Default(null, null), cachingFactory,
clientFactory) {
@Override
public Response execute(Request request, Request.Options options) {
Map<String, Collection<String>> headers = new HashMap<>(2);
headers.put("content-type", Collections.singletonList("application/json"));
headers.put("transfer-encoding", Collections.singletonList("chunked"));
Response.Builder builder = Response.builder()
.status(200).headers(headers)
.request(request);
try {
Response resp = super.execute(request, options);
if (Objects.equals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, resp.status())) {
log.error("服务内部错误, req: {}, data: {}", request.url(),
new String(Optional.ofNullable(request.body()).orElse(new byte[]{}, StandardCharsets.UTF_8));
return builder.body(JSONObject.toJSONBytes(RestResult.fail("服务内部错误"))).build();
}
return resp;
} catch (Exception e) {
log.error("服务不可用, req: {}, data: {}", request.url(),
new String(Optional.ofNullable(request.body()).orElse(new byte[]{}, StandardCharsets.UTF_8));
return builder.body(JSONObject.toJSONBytes(RestResult.fail("服务不可用"))).build();
}
}
};
}
}