1. 问题
在跑Demo案例时,没有遇见这个问题,在我们业务消费服务代码中创建
熔断器时产生了下面的问题,项目都跑不起来了。
Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘xxx.xxxService’ method
public abstract java.util.Map xxx.xxxService.listFAQ(java.lang.Integer,java.lang.String)
to {GET /api/web/v2/faq}: There is already ‘faqFallBack’ bean method
public java.util.Map xxx.xxxFallBack.listFAQ(java.lang.Integer,java.lang.String) mapped.
网上的答案: 报这个错的原因是因为你controller里的@RequestMapping中的路径有重复,检查了下,并没有重复的,BUG并不是这个原因
1.1环境
jdk8 + maven + idea + Spring全家桶
1.2 maven依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
1.3 配置
打开熔断器,默认是false
feign:sentinel:enabled:true
1.4 消费服务 Feign 使用
记得在入口类添加注解@EnableFeignClients
@FeignClient(value="provider-member",fallback= FaqFallBack.class)@RequestMapping("/api/web/v2")publicinterfaceFaqService{@RequestMapping(value="/faq",method= RequestMethod.GET)
MaplistFAQ(@RequestParam("pageNo")Integer pageNo,@RequestParam("distributor")String distributor);}
1.5 熔断器
@ComponentpublicclassFaqFallBackimplementsFaqService{@Overridepublic MaplistFAQ(Integer pageNo, String distributor){return Response.BAD("无法获取FAQ列表~");}}
2. 解决方案
通过工厂创建熔断器,解决了我的问题。。
2.1 工厂实现
import com.ezblock.consumermember.service.fallback.FaqFallBack;import feign.hystrix.FallbackFactory;import org.springframework.stereotype.Component;@ComponentpublicclassFaqServiceFallBackFactoryimplementsFallbackFactory<FaqFallBack>{@Overridepublic FaqFallBackcreate(Throwable throwable){returnnewFaqFallBack(throwable);}}
2.2 熔断器实现
不需要@Component注解,对每一个函数进行了熔断处理
publicclassFaqFallBackimplementsFaqService{private Throwable throwable;publicFaqFallBack(Throwable throwable){this.throwable= throwable;}@Overridepublic MaplistFAQ(Integer pageNo, String distributor){return Response.BAD("无法获取FAQ列表~");}}
2.3 消费服务 Feign调用
@FeignClient(value="provider-member",fallbackFactory= FaqServiceFallBackFactory.class)@RequestMapping("/api/web/v2")publicinterfaceFaqService{@RequestMapping(value="/faq",method= RequestMethod.GET)
MaplistFAQ(@RequestParam("pageNo")Integer pageNo,@RequestParam("distributor")String distributor);}