從零搭建springcloud微服務(五)----Feign調用服務接口


一、微服務搭建

1.參考之前的文章,創建用戶中心開放接口模塊user-open-api。

新增模塊依賴時,選擇

2.修改POM文件。

(1)cloud-provider和cloud-consumer模塊加上user-open-api的依賴

(2)cloud-dependencies模塊加上spring-cloud-dependencies依賴

 (3)michael-cloud項目增加user-open-api子模塊

 3.user-open-api模塊創建client和dto包

4.去掉自動生成的代碼

(1)新增UserRemoteClient接口

 (2)新增UseDto

 (3)修改CloudConsumerApplication類,類名上方加上@EnableFeignClients(basePackages = "com.plkd.usercenter.client")

(4)cloud-provider模塊新增

 (5)cloud-consumer模塊新增

5.啟動服務后,瀏覽器輸入http://localhost:8080/order/getUserByOrderId/2

服務調用成功

6.如果消費者需要消費多個不同的服務提供者,可以按照如下修改

@EnableFeignClients(basePackages = {"com.plkd.usercenter.client","com.plkd.usercenter.api"})

 

二、問題處理

1.系統提示以下異常:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderController': Unsatisfied dependency expressed through method 'setUserRemoteClient' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.plkd.usercenter.client.UserRemoteClient': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Method UserRemoteClient#findUserByUserName(String) not annotated with HTTP method type (ex. GET, POST)

解決方案:

方法上添加@RequestMapping(value = "/findUserByUserName/{userName}",method = RequestMethod.GET)

並增加@PathVariable

2.系統提示以下異常:

feign.FeignException$NotFound: [404] during [GET] to [http://cloud-provider/user/findUserByUserName?userName=michael] [UserRemoteClient#findUserByUserName(String)]: [{"timestamp":"2020-03-23T09:47:04.917+0000","status":404,"error":"Not Found","message":"No message available","path":"/user/findUserByUserName"}]

原因:路徑不對

修改成@RequestMapping(value = "/user/findUserByUserName/{userName}",method = RequestMethod.GET)即可

3.系統提示以下異常:

NotAllowed: [405] during [GET] to [http://cloud-user-center/user/name] [IUserOpenService#findUserByUserName(String)]: [{"timestamp":"2020-03-23T08:24:18.400+0000","status":405,"error":"Method Not Allowed","message":"Request method 'POST' not supported","path":"/user/name"}]

原因:如果feign代理的是get請求,則每個參數必須帶上@RequestParam,否則會報post not support!

解決方案:參數帶上@RequestParam("userName")

4.系統提示以下異常:

The bean 'cloud-provider.FeignClientSpecification' could not be registered. A bean with that name has already been defined and overriding is disabled.

原因:多個接口上的@FeignClient(“相同服務名”)會報錯,overriding is disabled,即出現了相同的Bean名。

解決方案:將@FeignClient("cloud-provider")修改成@FeignClient(name="cloud-provider", contextId = "cloud-provider-1")

參考文章:https://blog.csdn.net/u012211603/article/details/84312709


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM