Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API。
Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。
Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
简而言之:
Feign 采用的是基于接口的注解
使用 RestTemplate时 ,URL参数是以编程方式构造的,数据被发送到其他服务。
Feign是Spring Cloud Netflix库,用于在基于REST的服务调用上提供更高级别的抽象。Spring Cloud Feign在声明性原则上工作。使用Feign时,我们在客户端编写声明式REST服务接口,并使用这些接口来编写客户端程序。开发人员不用担心这个接口的实现。
再说,就是简化了编写,RestTemplate还需要写上服务器IP这些信息等等,而FeignClient则不用。
在SpringCloud(4):生产者和消费者注册及调用演示基础上进行修改,主要修改order-demo模块,修改如下:
3.1 添加pom文件
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-openfeignartifactId>
- dependency>
3.2 在启动类上,添加开feign注解
添加@EnableFeignClients注解如下:
- @SpringBootApplication
- @EnableEurekaClient
- @EnableFeignClients
- public class OrderApp {
- public static void main(String[] args) {
- SpringApplication.run(OrderApp.class, args);
- }
-
- @Bean
- @LoadBalanced
- RestTemplate restTemplate() {
- return new RestTemplate();
- }
- }
3.3定义接口
- package com.study.service;
-
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
-
- @FeignClient(value = "study-user")
- public interface FeignService
- {
- @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
- String getUser(@PathVariable("id") int id);
- }
3.4 使用feign
修改controller,修改方案如下:
- package com.study.controller;
-
- import com.study.service.FeignService;
- import com.study.service.OrderService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- public class OrderController {
-
- @Autowired
- FeignService feignService;
-
- @RequestMapping("/order2")
- public String addOrder2(String name, int id) { // 调用用户,查询用户信息,
- String result = feignService.getUser(id); return "商品:" + name + ",生成订单:" + result;
- }
-
- }