SpringCloud_Feign工程構建

1. 添加feign依賴包。

<!-- Feign 相關支持 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

2. 因爲Feign是一個聲明式WebService客戶端。使用Feign能讓編寫Web Service客戶端更加簡單,它的使用方法就是定義一個接口,然後在上面添加註解,所以首先創建一個接口,並添加註解聲明。

@FeignClient(value = "XXXXXXX(服務提供者名稱)")
public interface UserClientService {

    @GetMapping("/user/{userId}")
    JsonData get(@PathVariable("userId") Long userId);

    @GetMapping("/user/list")
    JsonData list();
}

3. 修改consumer的controller,使用注入Service的方式實現訪問提供者。

@RestController
@RequestMapping("/consumer/user")
public class UserControllerConsumer {

    @Autowired
    private UserClientService userClientService;

    @GetMapping("/{userId}")
    public JsonData get(@PathVariable("userId")  Long userId) {
        return userClientService.get(userId);
    }

    @GetMapping("/list")
    public JsonData selectList() {
        return userClientService.list();
    }
}

4.修改application啓動類,添加開啓feign客戶端的註解。

@EnableFeignClients(basePackages = {"com.xxx.xxx"})

警告:Feign坑!

首先,我以前寫controller接口的時候,對於url上帶有參數的接口,在方法中習慣類似 @PathVariable 這樣的簡寫,而不是像 @PathVariable(“userId”) 這樣寫全,以前沒有遇到任何的問題。直到寫Feign的時候,在Service中的簡寫了,然後就報錯,找了很久原因,才發現必須要聲明參數寫全,寫代碼不要偷懶啊!

錯誤寫法:

@FeignClient(value = "XXXXXXX(服務提供者名稱)")
public interface UserClientService {

    @GetMapping("/user/{userId}")
    JsonData get(@PathVariable Long userId);

    @GetMapping("/user/list")
    JsonData list();
}

正確寫法:

@FeignClient(value = "XXXXXXX(服務提供者名稱)")
public interface UserClientService {

    @GetMapping("/user/{userId}")
    JsonData get(@PathVariable("userId") Long userId);

    @GetMapping("/user/list")
    JsonData list();
}

發佈了45 篇原創文章 · 獲贊 7 · 訪問量 8299
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章