第六章:声明式服务调用:Spring Cloud Feign

  Spring Cloud Feign 是基于 Netflix Feign 实现的,整合了 Spring Cloud Ribbon 和 Spring Cloud Hystrix,除了提供这二者的强大功能以外,还提供了一种声明式的 Web 服务客户端定义方式。java

快速入门

  • 首先,建立一个 Spring Boot 基础工程,取名为 feign-consumer,并在 pom.xml 中引入 spring-cloud-starter-eureka 和 spring-cloud-starter-feign 依赖。具体内容以下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>feign-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>feign-consumer</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Dalston.SR2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
  • 在主类上经过 @EnableFeignClients 注解开启 Spring Cloud Feign 的支持功能。
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignConsumerApplication.class, args);
    }
}
  • 定义 HelloService 接口,经过 @FeignClient 注解指定服务名来绑定服务,而后再使用 Spring MVC 的注解来绑定具体该服务提供的 REST 接口。
@FeignClient(value = "hello-service")
public interface HelloService {

    @RequestMapping(value = "/index")
    String hello();
}

  注意:此处服务名不区分大小写,hello-service 和 HELLO-SERVICE 均可以使用。web

  • 接着,建立一个 ConsumerController 来实现对 Feign 客户端的调用。使用 @Autowired 直接注入上面定义的 HelloService 实例,并在 helloConsumer 函数中调用这个绑定了 hello-service 服务接口的客户端来向该服务发起 /index 接口的调用。
package com.example.demo.controller;

import com.example.demo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lxx
 * @version V1.0.0
 * @date 2017-8-16
 */

@RestController
public class ConsumerController {

    @Autowired
    HelloService helloService;

    @RequestMapping(value = "feign-consumer", method = RequestMethod.GET)
    public String helloConsumer(){
        return helloService.hello();
    }
}
  • 最后,同Ribbon实现的服务消费者同样,须要在 application.properties 中指定注册中心,并定义自身的服务名为 feign-consumer,为了方便本地调试与以前的 Ribbon 消费者的区分,端口使用 9991.
spring.application.name=feign-consumer

server.port=9991

eureka.client.service-url.defaultZone=http://localhost:8082/eureka/

测试验证

  和Ribbon实现时同样,启动 eureka-server 和 两个hello-service,而后启动 feign-consumer,发送请求到 http://localhost:9991/feign-consumer,正确返回。与 Ribbon 不一样的是,经过 Feign 咱们只需定义服务绑定接口,以声明式的方法,优雅而简单地实现了服务调用。spring

参数绑定

  上面介绍了一个不带参数的 REST 服务绑定。然而实际系统中的各类业务接口要复杂的多,咱们会在 HTTP 的各个位置传入不一样类型的参数,而且在返回请求响应的时候也多是一个复杂的对象结构。apache

  在开始介绍 Spring Cloud Feign 的参数绑定以前,先扩展一下服务提供方 hello-service 。增长下面这些接口定义,其中包含带有 Request 参数的请求、带有 Header 信息的请求、带有 RequestBody 的请求以及请求响应体中是一个对象的请求。api

package com.example.demo.web;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * @author lxx
 * @version V1.0.0
 * @date 2017-8-9
 */

@RestController
public class HelloController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/index")
    public String index(){
        ServiceInstance instance = client.getLocalServiceInstance();
        // 让处理线程等待几秒钟
        int sleepTime = new Random().nextInt(3000);
        logger.info("sleepTime:"+sleepTime);

        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("/hello:host:"+instance.getHost()+" port:"+instance.getPort()
                +" service_id:"+instance.getServiceId());
        return "hello world!";
    }


    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    public String hello1(@RequestParam String name){
        return "HELLO " + name;
    }


    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    public User hello2(@RequestHeader String name, @RequestHeader Integer age){
        return new User(name, age);
    }

    @RequestMapping(value = "/hello3", method = RequestMethod.POST)
    public String hello3(@RequestBody User user){
        return "HELLO," + user.getName()+","+user.getAge();
    }
}

  User 对象的定义以下,须要注意,这里必需要有User 的默认构造函数。否则,Spring Cloud Feign 根据 JSON 字符串转换 User 对象会抛出异常。app

package com.example.demo.web;

/**
 * @author lxx
 * @version V1.0.0
 * @date 2017-8-16
 */

public class User {
    private String name;

    private Integer age;

    public User() {
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

  完成对 hello-service 的改造以后,在 feign-consumer 应用中实现这些新增的请求的绑定。dom

  • 首先,在 feign-consumer 中建立与上面同样的 User 类。
  • 而后,在 HelloService 接口中增长对上述三个新增接口的绑定声明,修改后,完成的HelloService 接口以下所示:
package com.example.demo.service;

import com.example.demo.entity.User;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.*;

/**
 * @author lxx
 * @version V1.0.0
 * @date 2017-8-16
 */

@FeignClient(value = "hello-service")
public interface HelloService {

    @RequestMapping(value = "/index")
    String hello();

    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    String hello1(@RequestParam(value = "name") String name);

    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    User hello2(@RequestParam(value = "name") String name, @RequestHeader(value = "age") Integer age);

    @RequestMapping(value = "/hello3", method = RequestMethod.POST)
    String hello3(@RequestBody User user);
}

  注意:在参数绑定时,@RequestParam、@RequestHeader等能够指定参数名称的注解,他们的 value 不能少。在 Spring MVC 中,这些注解会根据参数名来做为默认值,可是在 Feign 中绑定参数必须经过 value 属性来指明具体的参数名,否则会抛出异常 IllegalStateException ,value 属性不能为空。maven

  • 最后,在 ConsumerController 中新增一个 /feign-consumer2 接口,来对本节新增的声明接口进行调用,修改后的完整代码以下所示:
package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lxx
 * @version V1.0.0
 * @date 2017-8-16
 */

@RestController
public class ConsumerController {

    @Autowired
    HelloService helloService;

    @RequestMapping(value = "feign-consumer", method = RequestMethod.GET)
    public String helloConsumer(){
        return helloService.hello();
    }

    @RequestMapping(value = "/feign-consumer2", method = RequestMethod.GET)
    public String helloConsumer2(){
        StringBuilder sb = new StringBuilder();
        sb.append(helloService.hello1("didi")).append("\n");
        sb.append(helloService.hello2("didi", 18)).append("\n");
        sb.append(helloService.hello3(new User("didi", 20))).append("\n");
        return sb.toString();
    }
}

  测试验证

  改造以后,启动服务注册中心、两个hello-service服务以及改造以后的 feign-consumer。经过发送请求到 http://localhost:9991/feign-consumer2 ,触发 HelloService 对新增接口的调用,获取以下输出:ide

继承特性

  经过上述的实践能够发现,当使用 Spring MVC 的注解绑定服务接口时,几乎能够从服务提供方的 Controller 中依靠复制操做,构建出相应的服务客户端绑定接口。既然存在那么多复制操做,天然须要考虑这部份内容是否能够获得进一步的抽象。在 Spring Cloud Feign 中,针对该问题提供了继承特性来帮助咱们解决这些复制操做,以进一步减小编码量。下面,详细看看如何经过 Spring Cloud Feign 的继承特性来实现 REST 接口定义的复用。函数

  • 为了可以复用 DTO 与接口定义,咱们先建立一个基础的 Maven 工程,命名为 hello-service-api。
  • 因为在 hello-service-api 中须要定义可同时复用于服务端与客户端的接口,咱们要使用到 Spring MVC 的注解,因此在 pom.xml 中引入 spring-boot-starter-web 依赖,具体内容以下所示:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>hello-service-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>hello-service-api</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
  • 将上一节中实现的 User 对象复制到 hello-service-api 工程中。
  • 在 hello-service-api 工程中建立 HelloService 接口,内容以下,该接口中的 User 对象为本项目中添加的 User。
package com.example.demo.service;

import com.example.demo.entity.User;
import org.springframework.web.bind.annotation.*;

/**
 * @author lxx
 * @version V1.0.0
 * @date 2017-8-16
 */

@RequestMapping(value = "/refactor")
public interface HelloService {

    @RequestMapping(value = "/hello4", method = RequestMethod.GET)
    String hello4(@RequestParam(value = "name") String name);

    @RequestMapping(value = "/hello5", method = RequestMethod.GET)
    User hello5(@RequestHeader(value = "name") String name, @RequestHeader(value = "age") Integer age);

    @RequestMapping(value = "/hello6", method = RequestMethod.POST)
    String hello6(@RequestBody User user);
}

  由于后续还会经过以前的hello-service 和 feign-consumer 来重构,为了不接口混淆,在这里定义 HelloService 时,除了头部定义了 /refactor 前缀以外,同时将提供服务的三个接口改名为 hello四、hello五、hello6.

  以上操做完成后,执行命令 mvn install 将该模块构建到本地仓库。

  • 下面对 hello-service 进行重构,在 pom.xml 的 dependency 节点中,新增对 hello-service-api 的依赖。
<dependency>
    <groupId>com.example</groupId>
    <artifactId>hello-service-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
  • 建立 RefactorHelloController 类实现 hello-service-api 中定义的 HelloService 接口,并参考以前的 HelloController 来实现这三个接口,具体内容以下:
package com.example.demo.web;

import entity.*;
import entity.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import service.HelloService;

/**
 * @author lxx
 * @version V1.0.0
 * @date 2017-8-16
 */

@RestController
public class RefactorHelloController implements HelloService {

    @Override
    public String hello4(@RequestParam(value = "name") String name) {
        return "HELLO " + name;
    }

    @Override
    public User hello5(@RequestHeader(value = "name") String name, @RequestHeader(value = "age") Integer age) {
        return new User(name, age);
    }

    @Override
    public String hello6(@RequestBody User user) {
        return "HELLO," + user.getName()+","+user.getAge();
    }
}
  • 完成了服务提供者的重构,接下来在服务消费者 feign-consumer 的 pom.xml 文件中,如在服务提供者同样,新增对 hello-service-api 的依赖。
  • 建立 RefactorHelloService 接口,并继承 hello-service-api 包中的 HelloService 接口,而后添加 @FeignClient 注解来绑定服务。(不能正常引用,先跳过)
相关文章
相关标签/搜索