1 Feign簡介
Feign是Netflix開發(fā)的聲明式愈腾、模板化的HTTP客戶端,在Spring Cloud中堡僻,對Feign添加了Spring MVC的支持观谦,并且整合了Ribbon和Eureka。
2 如何使用Feign
- 首先添加相應(yīng)的依賴:
<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-web</artifactId>
</dependency>
- 創(chuàng)建一個接口靴患,用注解
@FeignClient
聲明為Feign Client
@FeignClient(name = "eureka-client-demo")
public interface Client {
@GetMapping("/hello")
public String hello();
}
name屬性用來指定應(yīng)用名稱仍侥,用于創(chuàng)建Ribbon負(fù)載均衡器。還可以用url屬性指定url鸳君。
- 在啟動類中添加
@EnableFeignClients
注解
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class FeignDemoApplication {
public static void main(String[] args) {
SpringApplication.run(FeignDemoApplication.class, args);
}
}
- 配置(這里其實是Eureka的配置):
server:
port: 8004
spring:
application:
name: feign-demo
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/
instance:
prefer-ip-address: true
- 使用的時候直接調(diào)用Feign Client 聲明的方法即可农渊。
@RestController
public class Controller {
@Autowired
private Client client;
@GetMapping("/hello")
public String hello() {
return client.hello();
}
}