spring cloud feign会遇到什么坑

发布时间:2021-08-26 13:15:11 作者:小新
来源:亿速云 阅读:90

这篇文章将为大家详细讲解有关spring cloud feign会遇到什么坑,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

1:多客户端时,feign接口抽取到公共jar中,此时,客户端的启动类上需要对该jar中feign所在的包进行扫描,要在spring和feign中同时注册,否则启动时会报:“Consider defining a bean of type '******Feign' in your configuration.”

@SpringBootApplication
@EnableTransactionManagement
@EnableDiscoveryClient
@ComponentScan(basePackages={"com.lcamtech.aidis.feign","com.lcamtech.aiads.dts"})
@EnableFeignClients(basePackages = {"com.lcamtech.aidis.feign"})
@EnableCaching
@MapperScan(basePackages = "com.lcamtech.aiads.dts.mapper")
public class Application extends SpringBootServletInitializer{

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}

重点:

@ComponentScan(basePackages={"com.lcamtech.aidis.feign","com.lcamtech.aiads.dts"})
@EnableFeignClients(basePackages = {"com.lcamtech.aidis.feign"})

aidis包为包含feign的jar, 此时@ComponentScan还需要同时扫描本项目的包。

2:使用Fegin传值时,GET变POST

@FeignClient(value = "SERVICE-NAME")
public interface UserAccountFeign {

  @RequestMapping(value = "/ac/exist", method = RequestMethod.GET)
  public BaseResult isExist(@RequestParam("mobile") String mobile);

}

feign在传递时默认会将数据放在RequestBody中,所以会导致默认使用POST请求(及时@RequestMapping写着GET也没用),此时需要在参数列表中声明@RequestParam才能进行正常的GET请求。

3:feign请求返回复杂对象时

如:

public class Result{
 private string code;
 private string message;
 private Object data;

 //get/set
}

问题描述:当请求返回的是Result的一个对象时,对于该对象内部的data值,会变成一个linkedHashMap,并不会被转换成相应的类对象,若直接强转会报类型错误。

解决方法1:简单转换

/**
   * @Description: 将数据转换到相应的容器
   * @param bean
   * @param clazz
   * @return
   * @throws
   * @author SunF
   * @date 2018/6/20 10:28 
   */
  public static <T> T convertValue(Object bean, Class<T> clazz){
    try{
      ObjectMapper mapper = new ObjectMapper();
      return mapper.convertValue(bean, clazz);
    }catch(Exception e){
      log.error("错误的转换:BeanUtil.convertValue() --->" + e.getMessage());
      return null;
    }
  }

关于“spring cloud feign会遇到什么坑”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. 声明式HTTP客户端 - Spring Cloud OpenFeign
  2. 跟我学Spring Cloud(Finchley版)-01-开篇

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring cloud feign

上一篇:spring cloud eureka注册中心的示例分析

下一篇:Spring MVC启动过程的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》