天天看點

微服務【SpringCloud】--FeignFeign介紹Feign使用

文章目錄

  • Feign介紹
    • (1)Feign的音标
    • (2)Feign是什麼?
    • (3)Feign有什麼用?
    • (4)項目首頁:https://github.com/OpenFeign/feign
  • Feign使用
    • pom.xml
    • 開啟
    • 接口
    • CustomerController2

Feign介紹

(1)Feign的音标

美[feɪn] 假裝,裝作,佯裝

(2)Feign是什麼?

Feign開源庫,編寫 Http請求

(3)Feign有什麼用?

Feign makes writing java http clients easier

s讓編寫Http請求更容易,簡化拼接url,拼接參數等等操作

(4)項目首頁:https://github.com/OpenFeign/feign

Feign使用

(1)使用步驟

  • 導入啟動器依賴;
  • 開啟Feign功能;
  • 編寫Feign用戶端; 本質上是一個接口,Feign會生成實作類
  • 編寫一個處理器ConsumerFeignController,注入Feign用戶端并使用;
  • 測試

pom.xml

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

           

開啟

@EnableFeignClients//開啟feign
@SpringCloudApplication
public class Demo02ConsumerUser81Application
           

接口

//String url = "http://demo01-provider-user/users/"+id;
//調用demo01-provider-user提供者,擷取json資料,轉成User對象
@FeignClient("demo01-provider-user")
public interface UserClient {
    //定義方法
     @GetMapping("/users/{id}")
     User callProvider(@PathVariable long id);
}
           

CustomerController2

@RestController
@RequestMapping("/feign")
@Slf4j
public class CustomerController2 {
    @Autowired
    UserClient userClient;
    @RequestMapping(path = "/{id}", method = RequestMethod.GET)
    public Object get(@PathVariable long id) throws InterruptedException {
        User user = userClient.callProvider(id);
        return user;
    }

}