Feign结合Sentinel实现熔断,以及遇到的BUG

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.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>

1.3 配置

打开熔断器,默认是false

feign:
  sentinel:
    enabled: true

1.4 消费服务 Feign 使用

记得在入口类添加注解 @EnableFeignClients

@FeignClient(value = "provider-member",fallback = FaqFallBack.class)
@RequestMapping("/api/web/v2")
public interface FaqService {

    @RequestMapping(value = "/faq",method = RequestMethod.GET)
    Map listFAQ(@RequestParam("pageNo")Integer pageNo, @RequestParam("distributor")String distributor);

}

1.5 熔断器

@Component
public class FaqFallBack implements FaqService {

    @Override
    public Map listFAQ(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;

@Component
public class FaqServiceFallBackFactory implements FallbackFactory<FaqFallBack> {

       @Override
        public FaqFallBack create(Throwable throwable) {
            return new FaqFallBack(throwable);
        }
}

2.2 熔断器实现

不需要@Component注解,对每一个函数进行了熔断处理

public class FaqFallBack implements FaqService {

    private Throwable throwable;

    public FaqFallBack(Throwable throwable) {
        this.throwable = throwable;
    }

    @Override
    public Map listFAQ(Integer pageNo, String distributor) {
        return Response.BAD("无法获取FAQ列表~");
    }

}

2.3 消费服务 Feign调用

@FeignClient(value = "provider-member",fallbackFactory = FaqServiceFallBackFactory.class)
@RequestMapping("/api/web/v2")
public interface FaqService {

    @RequestMapping(value = "/faq",method = RequestMethod.GET)
    Map listFAQ(@RequestParam("pageNo")Integer pageNo, @RequestParam("distributor")String distributor);

}

Feign结合Sentinel实现熔断,以及遇到的BUG_第1张图片

参考文档

github:spring-cloud-alibaba sentinel结合fegin使用案例

你可能感兴趣的:(Spring,Cloud微服务,微服务)