Feign 概述
Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API。
Spring Cloud Feign帮助我们定义和实现依赖服务接口的定义。在Spring Cloud feign的实现下,只需要创建一个接口并用注解方式配置它,即可完成服务提供方的接口绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量
Feign的使用步骤
1:导入依赖
2:编辑接口
3:在启动类上增加注解
4:项目属性配置
5:业务代码,服务消费者调用服务提供者的服务
导入依赖
<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>
feign 的应用接口编辑
//polices 从注册中心中获取服务
@FeignClient(name = "polices")
public interface UserFeignClient {
@RequestMapping(value = "/call/{id}", method = RequestMethod.GET)
public String call (@PathVariable("id") Long id);
}
启动类上的注解
@SpringBootApplication
@EnableEurekaClient//eurea客户端注解
@EnableFeignClients//fegin客户端注解
public class FirstFeignApplication {
public static void main(String[] args) {
SpringApplication.run(FirstFeignApplication.class, args);
}
}
配置文件application.yml编写
server:
port: 7000
spring:
application:
name: first_feign
eureka:
client:
eureka-server-url:
defautZone: http://localhost:8761/eureka/
业务代码,服务消费者调用服务提供者的服务
@Controller
public class myController {
//注入Feign接口
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/router/{id}")
@ResponseBody
public String router(@PathVariable("id") Long id ) {
System.out.println("rout...");
// RestTemplate tpl = getRestTemplate();
// String json = tpl.getForObject("http://polices/call/1", String.class);
return userFeignClient.call(id);
}
public UserFeignClient getUserFeignClient() {
return userFeignClient;
}
public void setUserFeignClient(UserFeignClient userFeignClient) {
this.userFeignClient = userFeignClient;
}
}