前言
FeignClient 在调用服务时,目标端发生错误。
返回:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| { "code":"100005", "message":"error message", "data":"" }
FeignClient 接口定义为:
```java @FeignClient(name = "feignLogin"") public interface LoginFeign {
@GetMapping(value = "/api/feignUser") Result<User> feignUser(); }
|
这是 Feign 在序列化 Result<User>
时,会发生错误,
因为 “” 反序列化 User ,jackson 抛出异常。
经过反复测试,可以在拦截器上做统一的错误处理。
解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| @Slf4j @Configuration @ConditionalOnClass(Feign.class) @AutoConfigureBefore(FeignAutoConfiguration.class) public class FeignConfig {
@Bean @ConditionalOnMissingBean({Client.class}) public Client feignClient(okhttp3.OkHttpClient client) { return new feign.okhttp.OkHttpClient(client); }
@Bean public okhttp3.OkHttpClient okHttpClient() { return new okhttp3.OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .addInterceptor( new FeignInterceptor() ) .connectionPool( new ConnectionPool(10, 5L, TimeUnit.MINUTES) ) .build(); }
|
- FeignClient Interceptor 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class FeignInterceptor implements Interceptor {
@NotNull @Override public Response intercept(@NotNull Chain chain) throws IOException { Response response = chain.proceed(request); String responseBody = getResponseBody(response); Result<?> result = JsonUtil.toObject(responseBody, Result.class); if (!Result.SUCCESSED.getCode().equals(result.getCode())) { throw new BusinessException(result.getCode(), result.getMessage()); } return response; }; }
|
如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !