java B2B2C Springcloud仿淘寶電子商城系統-聲明式調用Feign之請求參數

一、Feign請求參數說明spring

  電子商務平臺源碼請加企鵝求求:一零三八七七四六二六。Feign是Netflix的產品,Spring Cloud Feign是在原生Feign的基礎上進行了封裝。因爲Spring Cloud Feign引入了許多springmvc的註解,方便springmvc的使用者使用,但同時也給使用者帶來了很大的混淆,下面咱們簡單講解一下springmvc和Spring Cloud Feign的參數綁定機制。api

1.1 SpringMVC請求參數綁定機制mvc

  咱們經過下面的例子進行講解:app

@RestController
public class demoController{
  @RequestMapping("hello")
  public String hello(String name){
    return "hello"+name;
  }
}

雖然接口很簡單,可是SpringMVC在解析請求時爲作了不少的事情微服務

@RequestMapping指定請求的路徑映射,咱們GET,POST,DELETE,PUT的請求均可以映射到這裏;url

SpringMVC提供的參數註解包括@RequestParm,@RequestBody,@PathVariable等,在例子中咱們的參數name被默認添加@RequestParm註解,SpringMVC使用字節碼技術獲取name這個名稱,自動檢測請求參數中key值爲name的參數,若是咱們的url請求或者form表單中包含name這個參數,就會被SpringMVC解析到。日誌

1.2 Spring Cloud Feign請求參數綁定機制code

  SpringMVC的參數綁定機制和Feign的參數綁定機制是不同的。下面咱們看一個錯誤的例子:orm

假若有這樣一個api:對象

@ResstController
public class demoController{
  @RequestMapping(value="hello",method=RequsetMethod.GET)
  public String hello(String name){
    return "hello"+name;
  }

Feign 訪問這個api

@FeignClient(name = "hello")  
public interface IHelloService {  
  @RequestMapping(value = "/hello",method = RequestMethod.GET)  
  String hello (String name);  
}

因爲咱們指定了請求方式GET,那麼若是按照SpringMVC的參數綁定機制,name參數會被拼接在URL上,可是接口並未接收到,查看後臺日誌發現:

請求方式不是GET,而是POST

name 參數爲null

通過Google發現Feign的參數綁定機制與SpringMVC不一樣:

Feign默認使用@RequestBody,這就是上面name參數爲null的緣由,@RequestBody(只能有一個)通常用於傳遞對象,若是參數中出現多個對象可使用Map來傳遞對象

@FeignClient(name = "hello")  
public interface IHelloService {  
  @RequestMapping(value = "/hello",method = RequestMethod.GET)  
  String saveBook(@RequestBody Book book);  
}
@FeignClient(name = "hello")  
public interface IHelloService {  
 @RequestMapping(value = "/hello",method = RequestMethod.GET)  
 String saveMap(@RequestParm Map map);  
}

Feign傳遞name參數,必須添加@RequestParm('name'),name必須指定,Feign不會利用SpringMVC字節碼的機制自動給定一個默認名稱

@FeignClient(name = "hello")  
public interface IHelloService {  
  @RequestMapping(value = "/hello",method = RequestMethod.GET)  
  String hello (@RequestParm('name') String name);  
}

二、@FeignClient註解與參數

  @FeignClient註解被@Target(ElementType.TYPE)修飾,代表@FeignClient註解的做用在接口上

2.1 @FeignClient標籤經常使用屬性

name:指定FeignClient的名稱,若是項目使用了Ribbon,name屬性會做爲微服務的名稱,用於服務發現

decode404:當發生http 404錯誤時,若是該字段位true,會調用decoder進行解碼,不然拋出FeignException

configuration: Feign配置類,能夠自定義Feign的Encoder、Decoder、LogLevel、Contract

fallback: 定義容錯的處理類,當調用遠程接口失敗或超時時,會調用對應接口的容錯邏輯,fallback指定的類必須實現@FeignClient標記的接口

fallbackFactory: 工廠類,用於生成fallback類示例,經過這個屬性咱們能夠實現每一個接口通用的容錯邏輯,減小重複的代碼

path: 定義當前FeignClient的統一前綴

相關文章
相關標籤/搜索