openfeign 增强解码器

OpenFeign 是一个Java编写的客户端负载均衡器,它使得编写Java HTTP客户端变得更加容易。如果你想要增强OpenFeign的解码器(Decoder)功能,通常是为了处理自定义的响应体解码逻辑或是支持额外的数据格式等。以下是一些方法来实现这一点:

1. 自定义解码器

你可以通过实现feign.Decoder接口来创建自定义解码器。这个接口有一个方法decode(),你需要根据响应来实现具体的解码逻辑。

@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);
        };
    }

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenFeign 中配置解码器可以通过自定义 FeignDecoder 来实现。以下是一个示例代码: 首先,你需要创建一个实现了 `Decoder` 接口的自定义解码器类,例如 `CustomDecoder`: ```java import feign.Response; import feign.codec.Decoder; import feign.jackson.JacksonDecoder; import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; public class CustomDecoder implements Decoder { private final ResponseEntityDecoder decoder; public CustomDecoder() { this.decoder = new ResponseEntityDecoder(new JacksonDecoder()); } @Override public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException { // 在这里可以进行自定义的解码逻辑处理 return decoder.decode(response, type); } } ``` 然后,在你的 Feign 接口上使用 `@Decoder` 注解来指定使用自定义的解码器,例如: ```java @FeignClient(name = "your-service", configuration = YourFeignClient.Config.class) public interface YourFeignClient { @GetMapping("/your-api") @Decoder(CustomDecoder.class) // 使用自定义的解码器 YourResponseObject yourApiMethod(); class Config { // 配置其它 Feign 相关的参数 } } ``` 这样,当调用 `YourFeignClient` 的 `yourApiMethod()` 方法时,将会使用自定义的解码器进行解码操作。 请注意,上述代码中的 `YourResponseObject` 是你期望的响应对象类型,你需要根据自己的实际情况进行替换。另外,还可以根据需要在 `CustomDecoder` 类中添加适合的解码逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值