自定义feign 解码器Decoder

说明

自定义feign的解码器Decoder需要实现feign.codec.Decoder接口,并重写decode方法,当接口在调用时发生了异常,则调用时不会走解码器(Decoder)逻辑,会走错误解码器(ErrorDecoder)的逻辑,反之亦然。自定义错误解码器和解码器方式相似,只是需要实现不同接口
解码器(Decoder) 实现feign.codec.Decoder
错误解码器(ErrorDecoder)实现feign.codec.ErrorDecoder
下面是以解码器为例:

自定义解码器

说明:重写方法decode中逻辑可以自定义

import com.alibaba.fastjson2.JSON;
import com.test.boot.param.FeignResultDto;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;

import java.io.IOException;
import java.lang.reflect.Type;

public class CustomDecoder implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        if (response == null || response.body() == null) {
            return new FeignResultDto<>(500, "返回空", null);
        }
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        return JSON.parseObject(bodyStr, type);
    }
}

局部生效

说明:只针对一个feignClient 接口生效,使用@FeignClient中的configuration指定即可

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.boot.config.CustomDecoder;
import com.test.boot.param.FeignResultDto;
import com.test.boot.param.PageQueryDto;
import com.test.boot.param.TransferImportListInDto;
import com.test.boot.param.TransferImportListOutDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@FeignClient(name = "stockFeign", url = "http://stock-center.net", configuration = {CustomDecoder.class})
public interface StockFeign {

    @PostMapping("/api/v1/transferorder/queryBatchImportTransferOrder")
    FeignResultDto<Page<TransferImportListOutDto>> queryBatchTransferOrder(@RequestBody PageQueryDto<TransferImportListInDto> pageQueryDto);

}

全局生效

说明:@FeignClient中的configuration无需指定,加个配置类即可

import feign.codec.Decoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomDecoderConfiguration {
    @Bean
    public Decoder feignDecoder() {
        return new CustomDecoder();
    }
}

当局部和全局类同时存在的时候,局部的生效

posted @ 2023-08-11 14:20  品书读茶  阅读(1674)  评论(0编辑  收藏  举报