关于在Spring Cloud Feign工程中使用Hystrix配置不生效的问题

   在《spring cloud 微服务实战》第211页--------Hystrix配置这一部分,书上说在Spring Cloud Feign中,还引入了服务保护与容错的工具Hystrix,默认情况下,Spring Cloud Feign会为将所有Feign客户端的方法都封装到Hystrix命令中进行服务保护。如果你用的是Dalston版本,请注意:Feign对Hystrix的支持默认是关闭的,如果想开启对Hystrix的支持,你不仅需要在application.properties中添加:
feign.hystrix.enabled=true
       而且需要添加hystrix的依赖,如果你是通过idea中的spring initializr 创建的spring cloud项目,你可以在pom文件中再添加:
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

       在Dalston版本中,要开启Feign对Hystrix的支持,这两个条件缺一不可,这些可以在spring cloud官方文档中找到说明。书上用的是Brixton版本,如果你按照书上的做可能不会成功,不同版本的spring cloud差异还是很大的。

       如果你按照上面的要求做了,还是不生效,原因是这样的:如果你从看这本书起,一直按照书上的案例来做,比如这一部分书上建的新项目是feign-consumer,当你按照书上讲的内容的顺序来做测试的话,比如看到第211页“禁用Hystrix”这一部分,你可能也新建了一个类:

@Configuration
public class DisableHystrixConfiguration {

    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder(){
        return Feign.builder();
    }
}

       这个类是通过使用@Scope("prototype")注解为指定的客户端配置Feign.Builder实例,从而构建一个关闭Hytrix的配置类,接下来书中就说让你在HelloService的@FeignClient注解中,通过configuration参数引入上面实现的配置:

@FeignClient(name = "hello-service", configuration = DisableHystrixConfiguration.class)
public interface HelloService {

    @RequestMapping("/hello")
    String hello();

    @GetMapping(value = "/hello1")
    String hello(@RequestParam("name") String name);

    @GetMapping(value = "/hello2")
    User hello(@RequestHeader("name") String name, @RequestHeader("id") int id);

    @PostMapping(value = "/hello3")
    String hello(@RequestBody User user);
}

       这样确实是实现禁用了,后来你又想测试服务降级配置,你又想开启对Hystrix的支持,然后想把@FeignClient注解中的configuration参数去掉就行了吧,例如:

@FeignClient(name = "hello-service", fallback = HelloServiceFallback.class)//,configuration = DisableHystrixConfiguration.class)
        运行后你按照第214页所讲的:先启动服务注册中心和feign-consumer,但是不启动hello-service服务。发送GET请求到http://localhost:9001/feign-consumer2,你会发现服务降级并没有生效,而且还报错了:com.netflix.client.ClientException: Load balancer does not have available server for client: hello-service 

       原因就是写的那个个配置类DisableHystrixConfiguration上面还有@Configuration注解:

@Configuration
public class DisableHystrixConfiguration {
       就算你在@FeignClient注解中没有引用该配置类,他也会被启动类上的注解扫描到(参见@SpringBootApplication注解中的@ComponentScan注解),所以跟着书上案例调试服务降级的时候记得把DisableHystrixConfiguration这个类全部注掉,然后满足那两个条件就OK了

       Dalston版本官网发布笔记关于Feign对Hystrix支持部分:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#spring-cloud-feign-hystrix

      还有为什么Feign对Hystrix的支持默认是关闭状态的原因讨论:https://github.com/spring-cloud/spring-cloud-netflix/issues/1277

转自:https://blog.csdn.net/lvyuan1234/article/details/77155919

猜你喜欢

转载自blog.csdn.net/wyxz126/article/details/80588165