一篇文章教你如何在SpringCloud项目中使用OpenFeign

 更新时间:2021年8月16日 12:00  点击:2377

OpenFeign的介绍

OpenFeign是一种声明式 、模板化的HTTP客户端。

何为声明式?

就像调用本地方法一样调用远程方法,无需感知操作远程http请求。

何为模板化?

Feign会为每一个Feign接口方法创建一个RequestTemplate对象,该对象封装了HTTP请求的全部信息,Feign的模板化就体现在这里。

OpenFeign与Feign的之间的关系

OpenFeign是由Feign演变过来,平时说的Feign指的是Netflix旗下的Feign,现在我们使用的是 OpenFeign是Pivotal 提供的。

注:Pivotal 公司可谓是大牛云集,公司的开源产品有:Spring 以及 Spring 衍生产品、Web 服务器 Tomcat、缓存中间件 Redis、消息中间件 RabbitMQ、平台即服务的 Cloud Foundry、Greenplum 数据引擎、还有大名鼎鼎的 GemFire(12306 系统解决方案组件之一)

Feign

Fegin是Spring Cloud组件中的轻量级RESTful的HTTP服务客户端,Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign本身不支持Spring MVC的注解,它有一套自己的注解

OpenFeign

OpenFeign是Spring Cloud 在Feign的基础上支持了Spring MVC的注解,如@RequesMapping等等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。

springcloud F 及F版本以上 springboot 2.0 以上基本上使用openfeign,openfeign 如果从框架结构上看就是2019年feign停更后出现版本,也可以说大多数新项目都用openfeign ,2018年以前的项目在使用feign

OpenFegin中的两个常用注解

@FeignClient:

用于通知Feign组件对该接口进行代理(不需要编写接口实现),使用者可直接通过@Autowired注入 。

@EnableFeignClients

Spring Cloud应用在启动时,Feign会扫描标有@FeignClient注解的接口,生成代理,并注册到Spring容器中。

在项目中使用OpenFeign

调用关系图

provider是具体的业务提供者,provider-api是对应服务抽出来的Api,供其他服务调用。假如provider-socre中需要调用中provider-vidoe的接口,须在provider-vidoe-api中暴露相应的接口,provider-socre中引入provider-vidoe-api的依赖,直接调用。

导入依赖

在服务中引入OpenFegin的依赖(provider-socre与provider-vidoe-api中都需要引入)

 <!--openfeign的依赖-->
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
      <version>2.2.1.RELEASE</version>
</dependency>

使用注解@FeignClient @EnableFeignClients

在provider-video-api中使用@FeignClient

@Component
@FeignClient(value="video")  //value值是对应的服务名
//通过声明式的注解,提供一个供其它服务调用的 Client。
public interface VideoBulletchatFeignApi {
    
    @GetMapping("/videoBulletchat/querySumBulletChat/{id}")
    public Wrapper querySumBulletChat(@PathVariable String id);
}

注意很重要:在video服务中需要有provider-video-api对应的实现

@RestController
@Slf4j
@RequestMapping("/videoBulletchat")
public class VideoBulletchatController {
    @Resource
    private VideoBulletChatService videoBulletChatService;
    @Value("${server.port}")
    private String port;
   
    @GetMapping("querySumBulletChat/{id}")
    public Wrapper querySumBulletChat(@PathVariable String id){
        log.info("视频id为 "+id+" 正在查询弹幕访问量!");
        log.info("端口号 "+port);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,Wrapper.SUCCESS_MESSAGE,videoBulletChatService.querySumBulletChat(id));
    }
}

在provider-score中使用@EnableFeignClients

/**
 * @author 小小张自由
 */
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class ScoreApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScoreApplication.class,args);
    }
}

注入对象、调用

在provider-score中引用OpenFegin依赖的同时,还要引用provider-video-api 的依赖

@Slf4j
@Service
public class ScoreService {

    @Autowired
    //当需要调用其他服务时,
    // 直接注入OpenFeign接口对象就可以像调用本地方法一样调用远程服务。
    private VideoBulletchatFeignApi feignApi;

   // 测试Feign
    public int testFegin(String id) {
        log.info("开始调用Fegin");
        Wrapper Result = feignApi.querySumBulletChat(id);
        log.info("调用Fegin返回成功!");
        return (Integer) Result.getResult();
    }

}

总结:

我们在主程序入口添加@EnableFeignClients注解开启对Feign Client扫描加载处理,根据Feign Client的开发规范,定义接口并添加@FeignClient注解。

当程序启动时,会进行包扫描,扫描所有@FeignClient的注解的类,并将这些信息注入Spring IOC容器中。当定义的Feign接口中的方法被调用时,通过JDK的代理的方式,来生成具体的RequestTemplate。当生成代理时,Feign会为每个接口方法创建一个RequestTemplate对象,该对象封装了HTTP请求的全部信息。如请求参数名、请求方法等信息都是在这个过程中确定的。

然后由RequestTemplate生成Request,然后把Request交给Client去处理。这里的Client可以是JDK原生的URLConnection、Apache的Http Client,也可以是OKhttp。最后Client被封装到LoadBalanceClient类,这个类结合Ribbon负载均衡发起服务之间的调用。

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注猪先飞的更多内容!

[!--infotagslink--]

相关文章