對比:Spring REST Templatespring
Spring Rest Template 爲調用REST services提供了一個很是簡單的方式。json
RestTempate restTemplate=new RestTemplate();//實例化或者依賴注入 String url="http://inventoryService/{0}";//提供目標URl(注意佔位符) Sku sku=template.getForObject(url,Sku.class,4724352);//調用URL,提供但願轉換的class,提供佔位符的值,Template負責全部HTTP和類型轉換
缺點:可是,這段代碼仍然須要app
Spring Cloud將在運行時實現負載均衡
建立一個interface,非Class單元測試
//標註由Feign/Spring 實現的接口 @FeignClient(url="localhost:8080/warehouse") public interface InventoryClient{ @RequestMapping(method=RequestMethod.GET,value="/inventory") List<Item> getItems(); @RequestMapping(method=RequestMethod.POST,value="/inventory/{sku}",consumes="application/json") void update(@PathVariable("sku") Long sku,@RequestBody Item item); }
注意:使用Spring Cloud的時候Feign還須要額外的依賴包測試
運行時實現url
Spring 掃描@FeignClientsspa
運行時提供實現rest
@SpringBootApplication @EnableFeignClients //Spring 會查找interfaces並實現它 public class Application{ }
就是這樣code
由Spring/Feign 提供實現
@FeignClient(url="localhost:8080/warehouse")
@FeignClient("warehouse")
Ribbon是自動啓用的
在運行時須要Feign Starter
但不是編譯時
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> </dependencies>