简介
Feign是Netflix开发的声明式、模板化的HTTP客户端,其灵感来自Retrofit、JAXRS-2.0以及WebSocket。Feign可帮助我们更加便捷、优雅地调用HTTP API。
在Spring Cloud中,使用Feign非常简单——只需创建接口,并在接口上添加注解即可。
Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。Spring Cloud对Feign进行了增强,使其支持Spring MVC注解,另外还整合了Ribbon和Eureka,从而使得Feign的使用更加方便。
创建spring-cloud-consumer-feign模块
pom.xml:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>spring-cloud-wsl</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-cloud-consumer-feign</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-consumer-feign</name>
<description>Demo project for Spring Cloud Consumer Feign</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
配置文件application.yml
server:
port: 8883
spring:
application:
# 指定注册到eureka server上的服务名称
name: consumer-feign
eureka:
client:
service-url:
# 指定eureka server通信地址,注意/eureka/小尾巴不能少
defaultZone: http://localhost:8761/eureka/
instance:
# 是否注册IP到eureka server,如不指定或设为false,那就会注册主机名到eureka server
prefer-ip-address: true
feign:
hystrix:
enabled: true
目录结构:
启动类添加@EnableFeignClients注解
@SpringBootApplication
@EnableFeignClients
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
feign接口:
@FeignClient(name = "provider")
public interface FeignTestClient {
@GetMapping("/test/{name}")
String test(@PathVariable String name);
}
controller:
@RestController
public class TestController {
@Autowired
private FeignTestClient feignTestClient;
@GetMapping("/feign/test/{name}")
public String test(@PathVariable String name) {
return feignTestClient.test(name);
}
}
依次启动eureka、两个provider,再启动spring-cloud-consumer-feign
浏览器输入http://localhost:8883/feign/test/wangshilin