簡介
Feign是Netflix開發(fā)的聲明式、模板化的HTTP客戶端,其靈感來自Retrofit庆尘、JAXRS-2.0以及WebSocket。Feign可幫助我們更加便捷巷送、優(yōu)雅地調(diào)用HTTP API驶忌。
在Spring Cloud中,使用Feign非常簡單——只需創(chuàng)建接口笑跛,并在接口上添加注解即可付魔。
Feign支持多種注解,例如Feign自帶的注解或者JAX-RS注解等飞蹂。Spring Cloud對Feign進行了增強几苍,使其支持Spring MVC注解,另外還整合了Ribbon和Eureka陈哑,從而使得Feign的使用更加方便妻坝。
創(chuàng)建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上的服務(wù)名稱
name: consumer-feign
eureka:
client:
service-url:
# 指定eureka server通信地址伸眶,注意/eureka/小尾巴不能少
defaultZone: http://localhost:8761/eureka/
instance:
# 是否注冊IP到eureka server,如不指定或設(shè)為false刽宪,那就會注冊主機名到eureka server
prefer-ip-address: true
feign:
hystrix:
enabled: true
目錄結(jié)構(gòu):
啟動類添加@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