好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Feign调用服务各种坑的处理方案

1.编写被调用服务

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@refreshscope

@restcontroller

public class xxxcontroller extends basecontroller implements indicatorsfeignapi{

     @resource

     private xxxservice xxx;

     @override

     public wrapper<commonvo> getxxxx(@requestbody commondto commondto) {

         try {

             commonvo vo = xxx.getdata(commondto);

             return wrapmapper.ok(vo);

         } catch (exception e) {

             e.printstacktrace();

             return wrapmapper.error( "系统异常,请联系管理员!" );

         }

     }

}

//service不进行展示,注意参数传递至service层时要加入注解@requestbody等才能获取参数

在配置文件添加feign相关配置

2.编写调用api

pom文件中添加相关依赖

?

1

2

3

4

org.springframework.cloud

spring-cloud-starter-hystrix

org.springframework.cloud

spring-cloud-starter-netflix-hystrix-dashboard

调用api

?

1

2

3

4

5

6

@feignclient(value = "被调用服务名" )

public interface indicatorsfeignapi {

 

  @postmapping(value = "/api/getxxxx" ,consumes= "application/json" , headers = { "accept=application/json" , "content-type=application/json" })

  wrapper<commonvo> getxxxx(@requestbody commondto commondto);

}

feign调用错误处理,发生相关错误是会跳转至fallback处理

?

1

2

3

4

5

6

7

8

@component

public class indicatorsfeignapihystrix implements indicatorsfeignapi {

  @override

  public wrapper<commonvo> getxxxx(commondto commondto) {

   system .out.println( "=====调用服务获数据发生异常======" );

   return null;

  }

}

当启用fallback后,有些报错不会打印在控制台上,这时可以修改配置中的

?

1

2

3

feign:

   hystrix:

     enabled: true

将enabled改为false,错误发生后将不会跳转fallback。

此处有一个坑,当时调用的时候服务是可以调用成功的,但是有一个报错:

could not extract response: no suitable httpmessageconverter found for response type [xxxx] and content type [text/html;charset=utf-8]

貌似是返回数据的编码与接收实体类不一样,导致报错。加上headers = {"accept=application/json", "content-type=application/json"}解决了相关问题.

3.编写客户端服务

?

1

2

3

4

5

6

7

8

9

10

11

12

13

//serviceimp层

    @autowired

  private indicatorsfeignapi api; //声明调用api

 

  @override

  public commonvo getxxx(commondto commondto) {

   wrapper<commonvo> result =   api.getxxxx(commondto); //服务调用

   if (result!=null) {

    return result.getresult();

   } else {

    return new commonvo();

   }

  }

微服务feign调用两边对象不一致

一开始以为feign调用,两边接收的对象必须一致

再发现两边对象的字段一致即可。

在之后遇到一个问题

a服务 a,b,两个字段+ getc()方法

b服务 a,b字段

出现异常序列化失败-----联想到前端解析json对象的方法,直接在b服务加上c字段,问题解决了...

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/weixin_35442221/article/details/103157639

查看更多关于Feign调用服务各种坑的处理方案的详细内容...

  阅读:16次