直接上代码
package com.haier.hibp.stock.config;
import com.alibaba.fastjson.JSON;
import com.haier.hibp.stock.constant.WebConstants;
import com.haier.hibp.stock.service.form.FeignResultDto;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.lang.reflect.Type;
@Configuration
public class CustomizedConfiguration {
@Bean
public Decoder feignDecoder() {
return new GenericsFeignResultDecoder();
}
}
class GenericsFeignResultDecoder implements Decoder {
@Override
public Object decode(Response response, Type type) throws IOException, FeignException {
if (response == null || response.body() == null) {
return new FeignResultDto<>(WebConstants.ERROR_CODE, WebConstants.INTERFACE_MESSAGE, null);
}
String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
return JSON.parseObject(bodyStr, type);
}
}
说明
1、上面的代码是自定义了一个返回值fastjson反序列化成对象的解码器
2、CustomizedConfiguration 类上的 @Configuration 如果加就全局生效。
3、CustomizedConfiguration 类上的 @Configuration 如果不加,可以在feign 接口上(如下面代码1所示),在feign 接口上,就作用于当前的feign 接口
代码1
@FeignClient(name = "stockFeign", url = "${feign.stock}", configuration = CustomizedConfiguration.class)
标签:feign,自定义,解码器,CustomizedConfiguration,Decoder,import,Configuration,stock
From: https://www.cnblogs.com/shareToAll/p/17622882.html