使用feign远程调用接口

项目中开发中,经常会用到调用其他项目的接口 或者第三方接口的情况,以前经常使用的是spring 的restTemplate 或者httpClient,但是使用每次都需要写一些公共的调用代码,比较麻烦。
feign 则能够比较好的解决了这个问题,不是spring cloud 项目也可以使用。

  • 一,是什么

feign 是Netflix 开发的声明式的http客户端,可以帮我们更加方便的调用http接口。在使用时候,就像调用本地方法一样,创建一个接口,然后在接口上添加一些注解,代码就可以完成了。spring Cloud 对feign进行了增强,使feign支持spring mvc 注解,并且整合了Ribbon 和Eureka,从而让Feign的使用更加的方便。

  • 二,怎么用
  1. 1.添加pom引用
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
         </dependency>
  1. 2.启动类添加@EnableFeignClients
@SpringBootApplication
@EnableFeignClients
public class DemoApplication {
   
   

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

  1. 3.创建service,添加@feignclient注解
/**
 * @创建人 
 * @创建时间 2020/12/10
 * @描述
 */
@FeignClient(value = "spring-boot-user", url = "http://test-ns.htexam.com/pand/common/mo",
        //fallback = HystrixClientFallBack.class
        fallbackFactory = HystrixClientFallBackFactory.class)
public interface UserFeignClient {
   
   

    @RequestMapping(value = "", method = RequestMethod.GET)
    Object findById();

}

@feignCient 注解中,value和name 是指定的要调用的服务ID,url是指定的访问的url地址,有时候,feignclient没有启动注册中心,那我们就需要启动feingclient中的url属性来表明被调用方。fallBack或fallBackFactory 是方法失败,可以回退调用的方法。

首先这是一个接口,feign通过动态代理,帮助我们生成实现类,通过value 指定要要调用的服务的名称。接口中的定义的方法,通过使用spring mvc 的注解,Feign会根据注解生成url,并且返回结果。

  1. 4.创建会退fallBack

    fallbackFactory与fallback方法不能同时使用,这个两个方法其实都类似于Hystrix的功能,当网络不通时返回默认的配置数据.

(1)fallBackFactory 方法

@Component
public class HystrixClientFallBackFactory implements FallbackFactory<UserFeignClient> {
   
   

    private Logger logger = LoggerFactory.getLogger(HystrixClientFallBackFactory.class);

    @Override
    public UserFeignClient create(Throwable throwable) {
   
   
      logger.error("failBack reason :{}",throwable.getMessage());
      //若发生错误,打印出来
      //failBack reason :status 404 reading UserFeignClient#findById()
        return new UserFeignClient() {
   
   
            @Override
            public Object findById() {
   
   
                StudentEntity studentEntity = StudentEntity.builder().userName("fallBackFactory 默认的用户名称").userId(456).age(12).build();
                return studentEntity;
            }
        };
    }
}

fallBack 回退之后,但是想要知道发生fallBack的原因,可以使用Logger打印出来,
logger.error(“fallback reason:{}”,throwable.getMessage());

(2)fallBack方式

直接实现UserFeignClient接口,然后重新servie方法

@Component
public class HystrixClientFallBack  implements  UserFeignClient{
   
   
    @Override
    public Object findById() {
   
   
        StudentEntity studentEntity = StudentEntity.builder().userId(123).userName("默认的用户姓名").age(12).build();
        return studentEntity;
    }
}

若配置了fallback,需要yml文件中配置,将熔断打开。

feign:
  hystrix:
    enabled: true # 开启feign的熔断功能
    #若为true,但是未配置fallBack类 FeignPaperService#getMapper() failed and no fallback available.

为了验证测试熔断fallBack机制,我将调用接口的url 改成错误的路由,并没有走到fallback类中去,而是抛错了。

status 404 reading UserFeignClient#findById()
原因就是未开启 feign:hystrix:enabled=true

  1. 5.单元测试
@Test
    public void testFeignUserService() {
   
   
        Object object = userFeignClient.findById();
        log.info("object信息是:{}" + object);//返回的是默认的 userName
    }
  • 三,openFeign 和 Feign的区别

    openFeign是Feign的升级版本,相同点:都是远程调用的组件,里面度配置了ribbon,都可以进行远程调用
    不同点:一个是spring-cloud-starter-feign,一个是spring-cloud-starter-openfeign

  • 四, 其他功能

    其他feign还支持负载均衡,Hystrix 熔断支持,请求压缩等。
    参考链接:
    feign声明式服务调用
    feign使用大全


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章