Springcloud的核心組件之Feign
假如現在有三個服務,入庫,庫存,出庫,這三個微服務是互相隔離的,那么微服務和微服務之間如何互相調用呢?顯然三個微服務都可以采用http通信,也就是可以采用Ribbon+restTemplate進行互相訪問(具體如何使用上篇文章講Ribbon組件有案例),但是這種方式對參數傳遞和使用都不是很方便,所以棄用此方式,采用Feign進行服務之間的調用,大大簡化調用過程。
Feign如何使用?
當我們使用feign客戶端時,一般要做以下三件事情 :
1:使用注解@EnableFeignClients啟用feign客戶端;
2:使用注解@FeignClient 定義feign客戶端;
3:使用注解@Autowired使用上面所定義feign的客戶端;
Feign使用案例
1: 當我們把服務都注冊到注冊中心,那么首先我們要在項目中引入Feign的依賴:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2:需要在啟動類添加@EnableFeignClients注解
@EnableFeignClients//啟用feign客戶端 @EnableDiscoveryClient @EnableEurekaClient @SpringBootApplication(scanBasePackages = {"com.wcf.client"}) public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } }
3:使用注解@FeignClient 定義feign客戶端
在調用方編寫接口類 //在調用方編寫接口類 @FeignClient(name = "provider-client") //name="provider-client"就是服務提供方暴露的接口名稱 public interface FeignTestInterface { @RequestMapping(value="/provider-feign/getInfo",method = RequestMethod.GET) //value="/provider-feign/getInfo"就是服務方暴露的接口地址 List<String> getNameInfo(@RequestParam("names") String[] names); }
4:在調用方的controller中調用接口:
使用注解@Autowired使用上面所定義feign的客戶端
@RestController public class FeignTestController { @Autowired private FeignTestInterface testInterface; @RequestMapping("/getNameInfo") public String config() { String[] names = {"李","王"}; return testInterface.getNameInfo(names).toString(); } }
5:在服務提供方提供如下方法:
@RestController @RequestMapping("/provider-feign") public class FeignTestController { @GetMapping("/getInfo") public List<String> Test(String[] names) { List<String> name = new ArrayList<String>(Arrays.asList(names)); name.add("郭"); return name; } }
服務提供方的配置文件如下
#服務端口 server.port=8077 #服務名稱,#即為上面@FeignClient注解的name值(name = "provider-client") spring.application.name=provider-client #服務地址 eureka.instance.hostname=localhost #取消檢索服務 eureka.client.fetch-registry=true eureka.client.register-with-eureka=true #注冊中心路徑,表示向這個注冊中心注冊服務,如果向注冊中心注冊多個服務,用“,”進行分隔 eureka.client.serviceUrl.defaultZone=http://localhost:8011/eureka
6:啟動並訪問
-
1:啟動注冊中心
-
2:啟動服務提供方
-
3:提供調用方服務
-
4:訪問地址:http://localhost:8091/getNameInfo

Feign機制:動態代理
Feign機制就是使用了動態代理。首先,如果你對某個接口定義了@FeignClient注解,Feign就會針對這個接口創建一個動態代理對象,
該對象生成動態代理時會根據代理類方法生成一個RequestTemplate,該對象封裝了HTTP請求需要的全部信息,如請求參數名、
請求方法等信息都在這個過程中確定,當請求該對象時候,會根據該對象封裝成Request去調用Http Client(默認JDK的URLConnection,可以替換成Okhttp等Http框架),
然后再委托Ribbon的LoadBalanceClient做負載均衡,完成服務之間的調用。

歡迎關注公眾號!公眾號回復:入群 ,掃碼加入我們交流群!
