springboot使用Feign用作第三方接口调用

1.步骤

  1. 引入openfeign的jar包
  2. 在启动类上加上**@EnableFeignClients**注解。
  3. 定义FeignClient,,如下:
@FeignClient(name = "feignClient",url = "${czb.support.url}",path = "/client/czb",configuration = {FeignErrorConfig.class})
public interface OrderFeignClient {
    @PostMapping("/sendCode")
    StatusResultModel sentCode(@RequestParam("tenant") String tenant, @RequestParam("phone") String phone);
}


public class FeignErrorConfig {
    @Bean
    public FeignErrorDecoder feignErrorDecoder(Gson gson){
        return new FeignErrorDecoder(gson);
    }
}
//返回状态非200时处理
public class FeignErrorDecoder implements ErrorDecoder {

    private Gson gson;

    public FeignErrorDecoder(Gson gson){
        this.gson = gson;
    }

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() == 417) {
            try {
                StatusResultModel statusResultModel = gson.fromJson(response.body().asReader(),
                        StatusResultModel.class);
                throw new HaveReasonException(statusResultModel.getMessage());
            } catch (JsonSyntaxException | JsonIOException | IOException e) {

                throw new HaveReasonException("未知错误");
            }
        }
        throw FeignException.errorStatus(methodKey, response);
    }
}

2.注意(坑)

  1. 记得增加@EnableFeignClients注解
  2. @FeignClient注解的url属性可以读取配置文件的配置
  3. @FeignClient注解的可以指定配置(配置类不需要加@Configuration),包括在返回状态不是200时的处理对象ErrorDecoder等。
  4. (使用低版本的springboot时需要注意)代理接口参数的@RequestParam注解需要填写name属性,值为被代理接口的参数接受名称,否则会报错如下:
RequestParam.value() was empty on parameter 0
  1. 代理接口的返回值接收类(复杂对象),将封装的数据对象定义定义为泛型,不要定义为Object,否则返回数据是将数据类属性及值封装到一个LinkedHashMap中。

3.关于反序列化对象是Object类型

我们Gson序列化工具为例:
代码如下:

	public static void main(String[] args) {
		Gson gson = new GsonBuilder().create();
		CzbBrand brand = new CzbBrand();brand.setId(1L);brand.setName("test");
		String str = gson.toJson(brand);
		System.out.println(str);
		Object a = gson.fromJson(str,Object.class);
		System.out.println(a);
	}

结果如下:反序列化类型为Object,则返回对象是将属性与属性值封装的LinkedTreeMap对象。
在这里插入图片描述
如果不是Object类型呢?
在这里插入图片描述是要求的对象。
这就是返回结果对象的Object数据属性无法成功反序列化,使用泛型就不会发生这样的问题。只不过Feign使用的其他序列化工具,用LinkedHashMap封装属性和属性值而已。

就一句忠告:
反序列化类型别指定为Object,除非你本来就想获得属性和属性值组成的键值对集合

发布了28 篇原创文章 · 获赞 11 · 访问量 1521

猜你喜欢

转载自blog.csdn.net/weixin_42881755/article/details/102584071