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

概要

  1. 什么是Spring Cloud Netflix Feign?

  2. 怎么用Feign?

什么是Spring Cloud Netflix Feign?

Feign:Declarative REST clients.
Feign:是一个声明式的REST客户端.
在之前的例子中我们使用的有DiscoveryClient,LoadBalancerClient,如他们一样FeignClient也是调用Eureka Server中服务用的,不过它提供了声明式的REST风格的调用,使编程更加简单.它是在运行时Runtime实现接口的实现,所以pom可以指定运行时依赖.

怎么用Feign?

百说不如一run,构造一个例子来实现

  1. Eureka Server 如之前一样,正常启动即可

  2. Eureka-Client 修改bootstrap.xml,变得简单一点,只有noun服务

spring:  application:    name: nounserver:  port: 8030eureka:  client:    service-url:      defaultZone: http://127.0.0.1:8010/eureka/
  1. Sentence-Client添加NounClient接口
@FeignClient("noun")public interface NounClient {    @RequestMapping(value = "/",method = RequestMethod.GET)    public  String getWord();}
  1. Sentence-Client添加pom.xml
            org.springframework.cloud            spring-cloud-starter-feign
  1. Sentence-Client在Application添加@EnableFeignClients

  2. Sentence-Client在SentenceController中使用NounClient

@RestControllerpublic class SentenceController {    @Autowired    private NounClient nounClient;    @RequestMapping("/sentence")    public @ResponseBody    String getSentence() {        return                "### 造句:[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;    }}
  1. 现在去http://127.0.0.1:8080/sentence检查下是否调用服务成功吧

特别感谢 kennyk65
Spring Cloud 中文用户组 31777218
Spring-Cloud-Config 官方文档-中文译本 (本人有参与,哈哈)
Spring Cloud Netflix 官网文档-中文译本
本文实例github地址 mmb-feign

关键字:产品经理

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部