spring cloud 學習(Feign)分散式配置中心
阿新 • • 發佈:2020-10-14
spring clound 之 Feign
Feign 是一個宣告式的 REST 客戶端,它用了基於介面的註解方式,很方便實現客戶端配置。
是一個簡化了RestTemplate呼叫以及 Ribbon的元件
1、操作步驟
- 匯入依賴
-
<!--feign--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
-
- 啟動類上添加註解@EnableFeignClients //開啟Feign的功能
-
1 @EnableDiscoveryClient // 啟用DiscoveryClient 2 @EnableEurekaClient 3 @SpringBootApplication 4 5 @EnableFeignClients //開啟Feign的功能 6 public class ConsumerApp { 7 public static void main(String[] args) { 8 SpringApplication.run(ConsumerApp.class
其餘註解不能刪除,都是基於Eureka來使用的
-
- 編寫feign介面
-
1 /** 2 * 3 * feign宣告式介面。發起遠端呼叫的。 4 * 5 String url = "http://FEIGN-PROVIDER/goods/findOne/"+id; 6 Goods goods = restTemplate.getForObject(url, Goods.class); 7 * 8 * 1. 定義介面 9 * 2. 介面上添加註解 @FeignClient,設定value屬性為 服務提供者的 應用名稱 10 * 3. 編寫呼叫介面,介面的宣告規則 和 提供方介面保持一致。
滿足的是將usrl進行拼接,能夠直接使用,提高複用性
-
- controller中的方法進行修改
-
1 @RestController 2 @RequestMapping("/order") 3 public class OrderController { 4 5 @Autowired 6 private GoodsFeignClient goodsFeignClient; 7 8 @GetMapping("/goods/{id}") 9 public Goods findGoodsById(@PathVariable("id") int id){ 10 11 Goods goods = goodsFeignClient.findGoodsById(id); 12 13 return goods; 14 } 15 }
-
2、Feign的超時設定
Feign底層依賴於Ribbon實現負載均衡和遠端呼叫
Ribbon預設1s超時
消費方進行配置
1 # 設定Ribbon的超時時間 2 ribbon: 3 4 ConnectTimeout: 1000 # 連線超時時間 預設1s 預設單位毫秒
消費方與提供發連線的時間 5 6 ReadTimeout: 3000 # 邏輯處理的超時時間 預設1s 預設單位毫秒
可以理解為 提供方執行需要執行的程式碼的所有時間,直到返回一個值給 消費方
feign也具有超時時間,底層依賴Ribbon 所以直接用Ribbon進行設定
3、Feign 的日誌記錄
Feign 只能記錄debug級別的日誌
操作步驟
1.配置
# 設定當前的日誌級別 debug,feign只支援記錄debug級別的日誌
logging:
level:
com.itheima: debug
2.定義Feign日誌級別Bean
1 @Configuration 2 public class FeignLogConfig { 3 /* 4 NONE,不記錄 5 BASIC,記錄基本的請求行,響應狀態碼資料 6 HEADERS,記錄基本的請求行,響應狀態碼資料,記錄響應頭資訊 7 FULL;記錄完成的請求 響應資料 8 */ 9 @Bean 10 public Logger.Level level(){ 11 return Logger.Level.FULL; 12 } 13 }
3.feign的配置類進行啟用
@FeignClient(value = "FEIGN-PROVIDER",configuration = FeignLogConfig.class) public interface GoodsFeignClient { @GetMapping("/goods/findOne/{id}") public Goods findGoodsById(@PathVariable("id") int id); }