0503-Hystrix保护应用-feign的hystrix支持

1、概述

1.一、基础【示例一】

  若是Hystrix在类路径上而且feign.hystrix.enabled = true,Feign将用断路器包装全部方法。还能够返回com.netflix.hystrix.HystrixCommand。这可以让您使用响应模式(调用.toObservable()或.observe()或异步使用(调用.queue())。git

  要以每一个客户端为基础禁用Hystrix支持,请建立一个具备“prototype”范围。github

  在Spring Cloud Dalston发布以前,若是Hystrix在类路径上,Feign默认状况下会将全部方法封装在断路器中。 Spring Cloud Dalston改变了这种默认行为,以支持选择加入方式。spring

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

1.二、Fallbacks【示例1、示例二】

  Hystrix支持回退的概念:当电路断开或出现错误时执行的默认代码路径。要为给定的@FeignClient启用回退,请将fallback属性设置为实现回退的类名称。您还须要将您的实现声明为Spring bean。app

@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

static class HystrixClientFallback implements HystrixClient {
    @Override
    public Hello iFailSometimes() {
        return new Hello("fallback");
    }
}

1.三、回退触发器的缘由fallbackFactory属性[示例三]

  若是须要访问做为回退触发器的缘由,则可使用@FeignClient中的fallbackFactory属性。  异步

  为指定的客户端接口定义一个回退工厂。回退工厂必须产生回退类的实例,这些实例实现由FeignClient注释的接口。ide

  若是同时设置fallback和fallbackfactory不能够有冲突,fallback生效,fallbackfactory不能使用,fallbackFactory 是fallback的一个升级版,注释fallback设置便可ui

@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
    @Override
    public HystrixClient create(Throwable cause) {
        return new HystrixClient() {
            @Override
            public Hello iFailSometimes() {
                return new Hello("fallback; reason was: " + cause.getMessage());
            }
        };
    }
}

 查看FallbackFactorythis

public interface FallbackFactory<T> {

  /**
   * Returns an instance of the fallback appropriate for the given cause
   *
   * @param cause corresponds to {@link com.netflix.hystrix.AbstractCommand#getExecutionException()}
   * often, but not always an instance of {@link FeignException}.
   */
  T create(Throwable cause);

  /** Returns a constant fallback after logging the cause to FINE level. */
  final class Default<T> implements FallbackFactory<T> {
    // jul to not add a dependency
    final Logger logger;
    final T constant;

    public Default(T constant) {
      this(constant, Logger.getLogger(Default.class.getName()));
    }

    Default(T constant, Logger logger) {
      this.constant = checkNotNull(constant, "fallback");
      this.logger = checkNotNull(logger, "logger");
    }

    @Override
    public T create(Throwable cause) {
      if (logger.isLoggable(Level.FINE)) {
        logger.log(Level.FINE, "fallback due to: " + cause.getMessage(), cause);
      }
      return constant;
    }

    @Override
    public String toString() {
      return constant.toString();
    }
  }
}
View Code

注意事项:在Feign中实施回退以及Hystrix回退的工做方式存在限制。目前,com.netflix.hystrix.HystrixCommand和rx.Observable的方法不支持回退。 url

2、示例区

示例1、feign使用hystrix

示例参看:https://github.com/bjlhx15/spring-cloud/tree/master/microservice-comsumer-movie-feign-with-hystrixspa

一、增长引用

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

二、增长配置启用

feign.hystrix.enabled=true

三、启动类增长注解

@EnableCircuitBreaker

四、增长UserFeignClient业务接口,并配置fallback 

@FeignClient(name = "microservice-provider-user", fallback = HystrixClientFallback.class)
public interface UserFeignClient {
    // @GetMapping("/sample/{id}")
    @RequestMapping(method = RequestMethod.GET, value = "/sample/{id}")
    public User findById(@PathVariable("id") Long id);
}

五、增长HystrixClientFallback类

@Component
public class HystrixClientFallback implements UserFeignClient {
    @Override
    public User findById(Long id) {
        User user = new User();
        user.setId(0L);
        return user;
    }
}

示例2、如何禁用单个FegionClient的Hystrix的支持

参考代码:https://github.com/bjlhx15/spring-cloud/tree/master/microservice-comsumer-movie-feign-customizing-without-hystrix

一、设置一遍如同上面

二、新增一个业务接口FeignClient2

@FeignClient(name = "xxxx", url = "http://localhost:8761/", configuration = Configuration2.class,fallback = FeignClient2Fallback.class)
public interface FeignClient2 {
    @RequestMapping(value = "/eureka/apps/{serviceName}")
    public String findServiceInfoFromEurekaByServiceName(@PathVariable("serviceName") String serviceName);
}

三、使用fallback 

@Component
public class FeignClient2Fallback implements FeignClient2 {
    @Override
    public String findServiceInfoFromEurekaByServiceName(String serviceName) {
        return "haha";
    }
}

四、使用的配置类

@Configuration
public class Configuration2 {
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("user", "a123");
    }

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

能够看到这里主要增长了feignBuilder建立

示例3、 回退触发器的缘由fallbackFactory属性

参考代码:

一、基本配置略

二、配置UserFeignClient 

@FeignClient(name = "microservice-provider-user",  fallbackFactory = HystrixClientFallbackFactory.class)
public interface UserFeignClient {
    // @GetMapping("/sample/{id}")
    @RequestMapping(method = RequestMethod.GET, value = "/sample/{id}")
    public User findById(@PathVariable("id") Long id);
}

注意:配置了fallbackFactory ,若是同时设置fallback和fallbackfactory不能够有冲突,只能设置一个,fallbackFactory 是fallback的一个升级版

三、fallbackFactory 的类设置HystrixClientFallbackFactory

@Component
public class HystrixClientFallbackFactory implements FallbackFactory<UserFeignClient> {
    private static final Logger logger = LoggerFactory.getLogger(HystrixClientFallbackFactory.class);

    @Override
    public UserFeignClient create(Throwable arg0) {
        HystrixClientFallbackFactory.logger.info("fallback reason was:{}", arg0.getMessage());
        return new UserFeignClientWithFactory() {
            @Override
            public User findById(Long id) {
                User user = new User();
                user.setId(-1L);
                return user;
            }
        };
    }
}

四、UserFeignClientWithFactory设置

public interface UserFeignClientWithFactory extends UserFeignClient {

}
相关文章
相关标签/搜索