SpringCloud-Feign (四)
前言
阅读之前先阅读
https://blog.csdn.net/dtttyc/article/details/88853525
Feign 是什么
Feign是web服务的客户端,只需要创建接口,只需要添加接口,然后在接口上添加注解,简单方便
为什么要使用Feign
- 不需要拼接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);
}
- 支持springmvc注解,并且整合Eureka和Ribbon
- 封装了http调用请求,更适合面试接口化的编程(动态代理实现)
Feign如何使用
- 引入pom文件
<!--Feign相关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
- 创建接口,在接口上使用@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);
- 在入口程序添加,使用注解 @EnableFeignClients和@ComponentScan
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
@ComponentScan("com.atguigu.springcloud")
- 注入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的区别
- ribbon 是一个基于http和tcp客户端的负载均衡
- feign是一个http客户端
- 调用方式不同,Ribbon是通过@ribbonClient
@RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration = MySelfRule.class)
- Feign是通过@EnableFeignClients
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
- Ribbon需要自己构建http请求 url, 然后通过RestTemplate发送
- Feign通过接口和注解的形式发送,底层是通过动态代理实现(暂时不深入讲解)
Eureka->ribbon->Feign
首先看一下整体的流程图
版权声明:本文为dtttyc原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。