# OpenFeign簡介
OpenFeign是一個聲明式Restful網絡請求客戶端。會根據帶有注解的函數信息構建網絡請求的模板,在發送網絡請求之前,OpenFeign會講函數的參數值設置到請求模板中。使用OpenFeign的Spring應用架構分為三個部分,分別為服務注冊中心、服務提供者和服務消費者。服務提供者向注冊中心注冊自己,然后消費者通過OpenFeign發送請求,OpenFeign會向服務注冊中心獲取服務提供者的信息,然后向提供者發送網絡請求。
OpenFeign默認使用Ribbon提供的負載均衡。
## 1.注冊中心
OpenFeign配合Eureka等服務注冊中心使用,Eureka為OpenFeign提供服務端信息的獲取,比如服務的IP地址和端口。
*****
## 2.服務提供者
服務端只需要提供對外的網絡請求接口,同時確保服務在應用注冊中心中注冊即可。
```
@RestController
@RequestMapping("/server")
public class FeignServerController{
@GetMapping("/instance/{serviceId}")
public Instance getInstanceByServiceId(@PathVariable("serviceId") String serviceId){
return new Instance(serviceId);
}
}
```
上述實現了API的接口,還需要將服務注冊到eureka上,application.yml設置相關信息和名稱,配置如下:
```
eureka:
instance:
instance-id: service1
client:
service-url:
default-zone: http://127.0.0.1:8761/eureka/
spring:
application:
name: feign-service
server:
port: 9000
```
*****
## 3.消費者
首先在pom文件添加eureka和openfeign的相關依賴,在入口添加@EnableFeignClients注解開啟OpenFeign自動化裝配。
```
@SpringBootApplication
@EnableFeignClients
public class FeignClientApplication{
public static void main(String[] args){
SpringApplication.run(FeignClientApplication.class,args);
}
}
```
接下來定義FeignClient接口,通過@FeignClient注解指定調用的遠程服務名稱,如下:
```
@FeignClient("feign-service")
@RequestMapping("/server")
public interface FeignClient{
@GetMapping()
}
```