概述:
OpenFeign是基于Spring的聲明式調用的HTTP客戶端,大大簡化了編寫Web服務客戶端的過程,用于快速構建http請求調用其他服務模塊。同時也是spring cloud默認選擇的服務通信工具。
使用方法:
?RestTemplate手動構建:
// 帶查詢參數的Get請求
String url = "https://api.example.com/users?name={name}&age={age}";
Map<String, Object> params = new HashMap<>();
params.put("name", "John");
params.put("age", 25);
User users = restTemplate.getForObject(url, User.class, params);
// 簡單Post請求
String url = "https://api.example.com/users";
User newUser = new User("John", "Doe");
User createdUser = restTemplate.postForObject(url, newUser, User.class);
OpenFeign聲明式接口:
相較于RestTemplate和OkHttp完整構建請求頭、請求體和url的過程。OpenFeign支持聲明服務接口類,并使用springMVC的風格定義請求(@RequestMapping)。
@FeignClient(name = " ",url=" ")
我們需要創建一個接口并使用@FeingClient注解聲明接口。
- 若沒有使用nacos,則我們需要在url中指定對應模塊的http地址(包含IP和端口)
- 若使用了nacos,則@FeingClient會通過name獲取對應實例列表(動態服務發現),并通過負載均衡獲取其中一個健康實例的IP和端口等信息(負載均衡)
- FeignClient最后會在FeignClientFactory中拼接模塊實例的IP、端口和當前接口方法的RequestMapping信息生成構建好的http客戶端對象(動態代理對象)并注入到spring容器中
// 啟用組件
@SpringBootApplication
@EnableDiscoveryClient // 啟用Nacos服務發現(可選,選擇后可通過FeignClient注解的name屬性獲取對應模塊實例列表)
@EnableFeignClients // 啟用OpenFeign(為FeignClient生成動態代理對象并注入到spring容器中)
public class Application { }
// 如果未結合服務注冊(Nacos)則需要硬編碼指定url
@FeignClient(name = "user-service",url = "")
public interface UserClient {@GetMapping("/users/{id}")User getUser(@PathVariable Long id);
}
// 掃描對應包下的FeignClient接口(一般放在公共依賴中)
@EnableFeignClients(basePackages = "com.example.feign.api")
@SpringBootApplication
public class OrderApplication { ... }
補充:
整合了OpenFeign和Nacos后才能通過name屬性發現nacos中注冊好的模塊實例列表,并通過Ribbon或LoadBalancer的負載均衡策略選擇適合的健康實例,構建對應的代理對象到spring容器中。
我們可以實現RequestInterceptor接口來對請求進行攔截,實現請求的精細控制。