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;
}
}