概要
什麼是Spring Cloud Netflix Feign?
怎麼用Feign?
什麼是Spring Cloud Netflix Feign?
Feign:Declarative REST clients.
Feign:是一個聲明式的REST客戶端.
在之前的例子中我們使用的有DiscoveryClient,LoadBalancerClient,如他們一樣FeignClient也是調用Eureka Server中服務用的,不過它提供了聲明式的REST風格的調用,使編程更加簡單.它是在運行時Runtime實現接口的實現,所以pom可以指定運行時依賴.
怎麼用Feign?
百說不如一run,構造一個例子來實現
-
Eureka Server 如之前一樣,正常啓動即可
-
Eureka-Client 修改bootstrap.xml,變得簡單一點,只有noun服務
spring:
application:
name: noun
server:
port: 8030
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8010/eureka/
-
Sentence-Client添加NounClient接口
@FeignClient("noun")
public interface NounClient {
@RequestMapping(value = "/",method = RequestMethod.GET)
public String getWord();
}
-
Sentence-Client添加pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
-
Sentence-Client在Application添加@EnableFeignClients
-
Sentence-Client在SentenceController中使用NounClient
@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