SpringCloud-Feign (四)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dtttyc/article/details/88863871

前言

阅读之前先阅读
https://blog.csdn.net/dtttyc/article/details/88853525

Feign 是什么

Feign是web服务的客户端,只需要创建接口,只需要添加接口,然后在接口上添加注解,简单方便

为什么要使用Feign

  1. 不需要拼接URl和参数,之前的操作
    @RequestMapping(value = "consumer/dept/get/{id}")
    public Dept get(@PathVariable("id")Long id) {
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class);
    }
  1. 支持springmvc注解,并且整合Eureka和Ribbon
  2. 封装了http调用请求,更适合面试接口化的编程(动态代理实现)

Feign如何使用

  1. 引入pom文件
    <!--Feign相关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
  1. 创建接口,在接口上使用@FeignClient(value=“服务名称”),需要注意的是他不可以是使用@GetMapping , 一般是在api端服务上
@FeignClient(value = "MICROSERVICECLOUD-DEPT")
public interface DeptClientService {
    @RequestMapping(value = "dept/get/{id}",method = RequestMethod.GET)
     Dept get(@PathVariable("id")long id);

  1. 在入口程序添加,使用注解 @EnableFeignClients和@ComponentScan
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
@ComponentScan("com.atguigu.springcloud")
  1. 注入api,实现api
    @Autowired
    private DeptClientService deptClientService;

    @RequestMapping(value = "/consumer/dept/get/{id}",method = RequestMethod.GET)
    Dept get(@PathVariable("id")long id){
       return this.deptClientService.get(id);
    }

ribbon与Feign的区别

  1. ribbon 是一个基于http和tcp客户端的负载均衡
  2. feign是一个http客户端
  3. 调用方式不同,Ribbon是通过@ribbonClient
@RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration = MySelfRule.class)
  1. Feign是通过@EnableFeignClients
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
  1. Ribbon需要自己构建http请求 url, 然后通过RestTemplate发送
  2. Feign通过接口和注解的形式发送,底层是通过动态代理实现(暂时不深入讲解)

Eureka->ribbon->Feign

首先看一下整体的流程图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/dtttyc/article/details/88863871