1、測試使用
(1)服務調用方引入依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.netflix.feign/feign-okhttp --> <dependency> <groupId>com.netflix.feign</groupId> <artifactId>feign-okhttp</artifactId> </dependency>
(2)服務調用方啟動類添加注解
@EnableFeignClients
(3)定義FeiClient接口
在服務調用方創建client包,專門用於定義FeiClient接口
@FeignClient("user-service-id") public interface UserClient { @GetMapping("/user/get/{id}") public User findById(@PathVariable("id") String id); }
(3)測試
啟動注冊中心Eureka、服務提供方工程
@Autowired private UserClient userClient; @Test public void testFeign(){ User user= userClient.findById("5a754adf6abb500ad05688d9"); System.out.println("testFeign:::::::::::::::::::"+JSONObject.toJSONString(user)); }
2、測試分析
(1)Feign 是netflix 開源的一個rest 客戶端,在這里替代了前面的RestTemplate + okhttp
(2)Feign同樣集成了Rebbion,實現了客戶端負載均衡,ribbon充當了一個負載均衡器
(3)使用體現: 在本地定義遠程接口、實現了像調用本地方法一樣進行遠程調用
3、工作原理:
(1)在啟動類上添加@EnableFeignClients 注解、spring 會掃描@FeignClient注解的接口、並生成其代理對象
(2)FeignClient 的value屬性指定了服務提供方服務名稱、Feign會從Eureka上獲取服務列表、通過負載均衡算法進行服務調用(Rebbion負載均衡器工作原理)
(3)springClould 對Feign進行了增強、使其兼容了SpringMvc注解,在接口方法上可以通過@GetMapping等注解進行url遠程調用,但是注意兩點
①參數必須使用@pathVariable、@RequestParam注解聲明、不能省略;
②返回值是對象類型、無參構造不能省略