什么是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