什麼是Spring Cloud Netflix Feign?html
怎麼用Feign?git
Feign:Declarative REST clients.
Feign:是一個聲明式的REST客戶端.
在以前的例子中咱們使用的有DiscoveryClient,LoadBalancerClient,如他們同樣FeignClient也是調用Eureka Server中服務用的,不過它提供了聲明式的REST風格的調用,使編程更加簡單.它是在運行時Runtime實現接口的實現,因此pom能夠指定運行時依賴.github
百說不如一run,構造一個例子來實現spring
Eureka Server 如以前同樣,正常啓動便可編程
Eureka-Client 修改bootstrap.xml,變得簡單一點,只有noun服務bootstrap
spring: application: name: noun server: port: 8030 eureka: client: service-url: defaultZone: http://127.0.0.1:8010/eureka/
Sentence-Client添加NounClient接口app
@FeignClient("noun") public interface NounClient { @RequestMapping(value = "/",method = RequestMethod.GET) public String getWord(); }
Sentence-Client添加pom.xmlui
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
Sentence-Client在Application添加@EnableFeignClientsurl
Sentence-Client在SentenceController中使用NounClientcode
@RestController public class SentenceController { @Autowired private NounClient nounClient; @RequestMapping("/sentence") public @ResponseBody String getSentence() { return "<h3>造句:</h3><br/>" + buildSentence() + "<br/><br/>" + buildSentence() + "<br/><br/>" + buildSentence() + "<br/><br/>" + buildSentence() + "<br/><br/>" + buildSentence() + "<br/><br/>" ; } public String buildSentence() { String sentence = "There was a problem assembling the sentence!"; try{ sentence = nounClient.getWord(); } catch ( Exception e ) { System.out.println(e); } return sentence; } }
如今去http://127.0.0.1:8080/sentence檢查下是否調用服務成功吧
特別感謝 kennyk65
Spring Cloud 中文用戶組 31777218
Spring-Cloud-Config 官方文檔-中文譯本 (本人有參與,哈哈)
Spring Cloud Netflix 官網文檔-中文譯本
本文實例github地址 mmb-feign