1 Feign简介
Feign是Netflix开发的声明式、模板化的HTTP客户端,在Spring Cloud中,对Feign添加了Spring MVC的支持,并且整合了Ribbon和Eureka。
2 如何使用Feign
- 首先添加相应的依赖:
<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>
- 创建一个接口,用注解
@FeignClient
声明为Feign Client
@FeignClient(name = "eureka-client-demo")
public interface Client {
@GetMapping("/hello")
public String hello();
}
name属性用来指定应用名称,用于创建Ribbon负载均衡器。还可以用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
- 使用的时候直接调用Feign Client 声明的方法即可。
@RestController
public class Controller {
@Autowired
private Client client;
@GetMapping("/hello")
public String hello() {
return client.hello();
}
}
网友评论