Spring Cloud 学习纪要二:Feign

Spring Cloud Feign:服务通信

  Spring Cloud Feign是简化Java HTTP客户端开发的工具,它的灵感来自于Retrofit、JAXRS-2.0和WebSocket。接下来将展示一个入门Demo。

开发环境 版本
IDEA 2018.2.6
JDK 1.8
Spring Boot 2.1.0
Spring Cloud Greenwich.M1

特别注意:本系列纪要环环相扣,建议从第一节开始阅读 点击跳转

新建项目

  在IDEA中通过Spring Initializr创建项目,选择Spring Boot 2.1.0版本、选择Maven依赖Web、Eureka Discovery(Cloud Discovery中)和Feign(Cloud Routing中)。

<dependencies>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-openfeignartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
    dependency>
dependencies>

加入注解

  在入口类添加@EnableEurekaClient和@EnableFeignClients注解。

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class FeignConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignConsumerApplication.class, args);
    }
}

添加配置

  在文件application.yml添加配置。

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    #    hostname: ConsumerName

spring:
  application:
    name: consumer

编写接口

  在上一篇的provider项目中,新建简单的Controller,代码如下,运行provider项目,访问http://localhost:8081/hello/chung可得到Hello Chung By Provider

@RestController
@RequestMapping("/hello")
public class HelloController {
    @GetMapping("/chung")
    public String helloChung(){
        return "Hello Chung By Provider";
    }
}

  在本篇的新项目consumer中新建接口和Controller,代码如下:

@FeignClient(name = "provider")
public interface ProviderClient {
    @GetMapping(value = "/hello/chung")
    String hello();
}
@RestController
@RequestMapping("hello")
public class HelloController {
    @Autowired
    private ProviderClient providerClient;

    @GetMapping("/consumer")
    public String hello(){
        return providerClient.hello();
    }
}

运行项目

  在VM options设置-DServer.port=8091,运行consumer项目,可以在Eureka页面看到本项目注册成功,访问http://localhost:8091/hello/consumer同样可以得到Hello Chung By Provider,证明服务间通信正常。
Spring Cloud 学习纪要二:Feign_第1张图片

附件

本系列纪要博客源码:跳转到github
本系列纪要博客配置文件:跳转到github

你可能感兴趣的:(Java,Spring,Cloud,Spring,Cloud,学习纪要,Spring,Cloud)