Spring Cloud实战(四)-Spring Cloud Netflix Feign

概要

  • 什么是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.cloudgroupId>
            <artifactId>spring-cloud-starter-feignartifactId>
        dependency>
  • Sentence-Client在Application添加@EnableFeignClients

  • Sentence-Client在SentenceController中使用NounClient

@RestController
public class SentenceController {

    @Autowired
    private NounClient nounClient;
    @RequestMapping("/sentence")
    public @ResponseBody
    String getSentence() {
        return
                "

造句:


"
+ buildSentence() + "

"
+ buildSentence() + "

"
+ buildSentence() + "

"
+ buildSentence() + "

"
+ buildSentence() + "

"
; } 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

原文地址:https://segmentfault.com/a/1190000006188802

你可能感兴趣的:(微服务,Spring,Cloud)