Spring Cloud Feign 是基于 Netflix Feign 实现的,整合了 Spring Cloud Ribbon 和 Spring Cloud Hystrix,除了提供这二者的强大功能以外,还提供了一种声明式的 Web 服务客户端定义方式。java
<?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>
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); } }
@FeignClient(value = "hello-service") public interface HelloService { @RequestMapping(value = "/index") String hello(); }
注意:此处服务名不区分大小写,hello-service 和 HELLO-SERVICE 均可以使用。web
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(); } }
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
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
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 接口定义的复用。函数
<?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>
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 将该模块构建到本地仓库。
<dependency> <groupId>com.example</groupId> <artifactId>hello-service-api</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
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(); } }