OpenFeign是一个Java库,用于简化HTTP客户端的编写。它使用注解来声明HTTP请求,并通过处理HTTP请求的响应与连接,使得开发者能够更容易地调用RESTful服务。然而,在处理HTTP响应时,默认的解码器可能无法满足所有复杂场景的需求,尤其是当响应体包含特殊格式或需要定制化处理时。这时,我们就需要考虑使用自定义的解码器(Decoder)来增强OpenFeign的功能。
自定义解码器:
代码实现:
package com.beimao.decoder;
import cn.hutool.core.util.TypeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.smart.core.exception.BizException;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
@Slf4j
public class FeignResponseDecoder implements Decoder{
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
try {
//判断响应是否为null,对应着openfeign请求有没有成功
if (response.body() == null) {
throw new DecodeException(response.status(), "没有数据响应", response.request());
}
//将响应的数据转成 字符串
String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
//再次将响应的数据转换成JSON类型
JSONObject jsonObject = JSONUtil.parseObj(bodyStr, true);
log.warn("openfeign解析消息:{}",jsonObject.get("msg"));
//获取json对象的code值,并判断是否为0,如果不为0抛出异常
int code = (int) jsonObject.get("code");
if (code != 0) {
throw new BizException(code, jsonObject.get("msg").toString());
}
//从json对象中获取data并转成 string类型
String dataStr = jsonObject.get("data").toString();
//获取返回的type的类型(是data的类型)的全路径名(引用类型)
Class<?> aClass = TypeUtil.getClass(type);
Object result = null;
//判断返回类型是否是List类型(因为list类型需要手动转化,List类型中有泛型,Object类型不能转)
if (aClass.isAssignableFrom(List.class)) {
//获取到List泛型中的类型
Type typeArgument = TypeUtil.getTypeArgument(type);
//将Type类型的 typeArgument 转化成Class类型
Class<?> aClass2 = TypeUtil.getClass(typeArgument);
//将data字符串转换 成 List泛型中的类型,并组合成List类型
result = JSONUtil.toList(dataStr, aClass2);
} else {
if (aClass.getName().startsWith("java.lang")) {
// 是Java自带类型
result=jsonObject.get("data");
} else {
// 不是Java自带类型
result = JSONUtil.toBean(dataStr, aClass);
}
}
return result;
} catch (Throwable ex) {
throw new DecodeException(1111, "openfeign解析错误", response.request());
}
}
}
当远程调用时,进行解析时,如果用到token,需要从请求头中获取,使其贯穿整个链路
代码如下:
@Configuration
public class FeignConfig {
@Bean
public Decoder decoder() {
return new FeignResponseDecoder();
}
@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String token = request.getHeader("token");
requestTemplate.header("token", token);
String traceId = MDC.get("traceId");
requestTemplate.header("traceId", traceId);
};
}
}