SpringCloud Feign 之 Fallback初体验

SpringCloud Feign 之 Fallback初体验

在微服务框架SpringCloud中,Feign是其中非常重要且常用的组件。Feign是声明式,模板化的HTTP客户端,可以帮助我们更方便快捷调用HTTP API。本文主要针对Feign的熔断机制Fallback进行简单介绍。Fallback主要是用来解决依赖的服务不可用或者调用服务失败或超时,使用默认的返回值。

1.引入Feign

  • pom依赖包

    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-feign</artifactId>
                <version>1.4.7.RELEASE</version>
    </dependency>
    
  • 启动类Application增加注解

    @SpringBootApplication(scanBasePackages = {"com.xiaoqiang.feigncomsumer"})
    @EnableFeignClients(basePackages = {"com.xiaoqiang.feigncomsumer"})
    @EnableEurekaClient
    public class FeigncomsumerApplication {
        public static void main(String[] args) {
            SpringApplication.run(FeigncomsumerApplication.class, args);
        }
    
    }
    
  • 接口类配置

    @FeignClient(name = "${feign.provider}",path = "/feignprovider")
    @Component
    public interface StudentClient {
    
         @GetMapping("/stud/getStudentList")
         List<Student> getStudentList(@RequestParam(required = false,name = "name") String name);
    }
    

2.Fallback配置

  • FallBack类

这里有一点需要注意的是@RequestMapping中的value,也就是url,不能与接口类中的url一样。因为一个URL不能映射到两个方法上。

@Component
@RequestMapping("fallback/")
public class  FallBackStudentClient implements StudentOtherClient {

    @Override
    public Student getStudent(String name) {
        Student student = new Student();
        student.setAge(0);
        student.setName("fall back test");
        return student;
    }
}
  • 接口类

    在@FeignClient注解的参数指定Fallback类,且需要@Component注解。

@Component
@FeignClient(name = "${feign.provider}",path = "/feignprovider"
        ,fallback = FallBackStudentClient.class)
public interface StudentOtherClient {
    @GetMapping("/stud/getStudent")
    Student getStudent(@RequestParam(required = false, name = "name") String name);
}

  • 打开Hystrix熔断功能

    在bootstrap.yml中增加Hystrix配置。其中Hystrix的默认time-out时间为1s。

    feign:
      name: MFRAMEWORK-PROVIDER
      provider: feignprovider
    ##开启Hystrix断路器
      hystrix:
        enabled: true
    

以上就是Figen的Fallback初体验的全部内容了。

demo地址:https://github.com/lanxuan826/sample-library/tree/master/feigndemo-fallback

ps:在测试过程遇到了一个问题,错误内容如图。

原因:多个接口上的@FeignClient(“相同服务名”)会报错,overriding is disabled。

解决:

在application.yml中配置:

spring
	main:  allow-bean-definition-overriding: true
posted @ 2019-09-08 21:19  指尖逆苍穹  阅读(9974)  评论(1编辑  收藏  举报
AmazingCounters.com