从零搭建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

posted @ 2020-03-23 18:35  michaelqmd  阅读(2207)  评论(0编辑  收藏  举报