一、之前項目存在的問題
我們這樣去調用微服務:
是不是感覺不好啊,怎麼可能去拼字符串呢?low爆了對吧。我們的Feign組件就是解決這個問題滴!
二、Feign組件
1、簡介
-
Feign可幫助我們更加便捷,優雅的調用HTTP API。
-
在SpringCloud中,使用Feign非常簡單——創建一個接口,並在接口上添加一些註解,代碼就完成了
-
Feign支持多種註解,例如Feign自帶的註解或者JAX-RS註解等。
-
SpringCloud對Feign進行了增強,使Feign支持了SpringMVC註解,並整合了Ribbon和Eureka,從而讓Feign的使用更加方便。
2、項目中實現
項目仍然是這個項目。
首先我們在order-service這裏面加入一些依賴。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
創建一個類
package com.springcloud.demo.feign;
import com.springcloud.demo.entity.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "service-product")
public interface ProductFeginClient {
@RequestMapping(value = "/product/{id}", method = RequestMethod.GET)
public Product findById(@PathVariable("id") Long id);
}
- 定義各參數綁定時,@PathVariable、@RequestParam、@RequestHeader等可以指定參數屬 性,在Feign中綁定參數必須通過value屬性來指明具體的參數名,不然會拋出異常。
-
@FeignClient:註解通過name指定需要調用的微服務的名稱,用於創建Ribbon的負載均衡器。 所以Ribbon會把 shop-service-product 解析爲註冊中心的服務。
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private ProductFeginClient productFeginClient;
@RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
public Product findById(@PathVariable Long id) {
Product product = productFeginClient.findById(id);
return product;
}
}
直接注入調用。啓動測試。可以成功!!!
3、實現負載均衡
feign:
client:
config:
feignName: #定義FeginClient的名稱
# 相當於Request.Options
connectTimeOut: 5000
# 相當於Request.Options
readTimeout: 5000
# 配置Feign的日誌級別,相當於代碼配置方式中的Logger
loggerLevel: full
# Feign的錯誤解碼器,相當於代碼配置方式中的ErrorDecoder
errorDecoder: com.example.SimpleErrorDecoder
# 配置重試,相當於代碼配置方式中的Retryer
retryer: com.example.SimpleRetryer
# 配置攔截器,相當於代碼配置方式中的RequestInterceptor
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
decode404: false
-
feignName:FeginClient的名稱
-
connectTimeout : 建立鏈接的超時時長
-
readTimeout : 讀取超時時長
-
loggerLevel: Fegin的日誌級別
-
errorDecoder :Feign的錯誤解碼器
-
retryer : 配置重試
-
requestInterceptors : 添加請求攔截器
-
decode404 : 配置熔斷不處理404異常
4、請求壓縮
feign:
compression:
request:
# 開啓請求壓縮
enabled: true
response:
# 開啓響應壓縮
enabled: true
feign:
compression:
request:
# 開啓請求壓縮
enabled: true
# 設置壓縮的數據類型
mime-types: text/html,application/xml,application/json
# 設置觸發壓縮的大小下限
min-request-size: 2048
5、日誌級別
在消費者那設置
# 設置服務的日誌
# NONE:不輸出日誌
# BASIC:用於生產環境測試追蹤問題
# HEADERS:basic的基礎上+ 請求頭和響應頭信息
# FULL:記錄所有
feign:
client:
config:
service-product:
loggerLevel: FULL
logging:
level:
com.springcloud.demo.feign.ProductFeginClient: debug
重新啓動項目。訪問接口,打印輸出
源碼的話,拿到之前文章的項目,修改一下就可以了