1. 程式人生 > 其它 >微服務中使用openfeign呼叫get請求注意事項

微服務中使用openfeign呼叫get請求注意事項

技術標籤:springcloudjava

當使用openfeign傳送get請求的時候總會遇到一些奇怪的問題,現在整理如下:

一.程式碼的實現方式如下,介面宣告都是普通的get請求,請求引數沒有做任何的處理:

客戶端控制層

@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;

    @GetMapping("hello")
    public String hello( String id){
        return helloService.getPaymentById(id);
    }
}
@FeignClient(contextId ="provider",value = "nacos-hello-provider")
public interface HelloService {
    /**
     *  
     * @param id
     * @return
     */
    @GetMapping(value = "/hello/get")
    String getPaymentById(String id);
}

遠端被呼叫介面程式碼

@RestController
@RequestMapping("hello")
public class HelloController {
    @GetMapping("/get")
    public String hello(String id){
        return "請求成功,收到的引數是:"+id;
    }

結論:

【1】測試報錯,後端日誌狀態 405

【2】如果此時將遠端介面的@GetMapping換成 @RequestMapping如下圖,再次請求測試,沒有報錯,但是引數沒有接收到,這裡猜測是openfeign將get請求轉成了post請求

@RestController
@RequestMapping("hello")
public class HelloController {
     @RequestMapping("/get")
     public String hello(String id){
        return "請求成功,收到的引數是:"+id;
    }

【3】如果將宣告的介面的引數宣告一個 @RequestParam("id") ,然後測試,遠端介面正常訪問,介面可以接收到引數

@FeignClient(contextId ="provider",value = "nacos-hello-provider")
public interface HelloService {
    /**
     *  
     * @param id
     * @return
     */
    @GetMapping(value = "/hello/get")
    String getPaymentById(@RequestParam("id") String id);
}

結論就是:當使用openFeign傳送get請求的時候,要在宣告的介面中需要使用 @RequestParam 註解 或者 restful相關注解 確定對映關係 否則報錯 405