0503-Hystrix保护应用-feign的hystrix支持
一、概述
1.1、基础【示例一】
如果Hystrix在类路径上并且feign.hystrix.enabled = true,Feign将用断路器包装所有方法。还可以返回com.netflix.hystrix.HystrixCommand。这可让您使用响应模式(调用.toObservable()或.observe()或异步使用(调用.queue())。
要以每个客户端为基础禁用Hystrix支持,请创建一个具有“prototype”范围。
在Spring Cloud Dalston发布之前,如果Hystrix在类路径上,Feign默认情况下会将所有方法封装在断路器中。 Spring Cloud Dalston改变了这种默认行为,以支持选择加入方式。
@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}
1.2、Fallbacks【示例一、示例二】
Hystrix支持回退的概念:当电路断开或出现错误时执行的默认代码路径。要为给定的@FeignClient启用回退,请将fallback属性设置为实现回退的类名称。您还需要将您的实现声明为Spring bean。
@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.3、回退触发器的原因fallbackFactory属性[示例三]
如果需要访问作为回退触发器的原因,则可以使用@FeignClient中的fallbackFactory属性。
为指定的客户端接口定义一个回退工厂。回退工厂必须产生回退类的实例,这些实例实现由FeignClient注释的接口。
如果同时设置fallback和fallbackfactory不可以有冲突,fallback生效,fallbackfactory不能使用,fallbackFactory 是fallback的一个升级版,注释fallback设置即可
@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());
}
};
}
}
查看FallbackFactory
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();
    }
  }
}
注意事项:在Feign中实施回退以及Hystrix回退的工作方式存在限制。目前,com.netflix.hystrix.HystrixCommand和rx.Observable的方法不支持回退。
二、示例区
示例一、feign使用hystrix
示例参看:https://github.com/bjlhx15/spring-cloud/tree/master/microservice-comsumer-movie-feign-with-hystrix
1、增加引用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、增加配置启用
feign.hystrix.enabled=true
3、启动类增加注解
@EnableCircuitBreaker
4、增加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);
}
5、增加HystrixClientFallback类
@Component
public class HystrixClientFallback implements UserFeignClient {
@Override
public User findById(Long id) {
User user = new User();
user.setId(0L);
return user;
}
}
示例二、如何禁用单个FegionClient的Hystrix的支持
1、设置一遍如同上面
2、新增一个业务接口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);
}
3、使用fallback
@Component
public class FeignClient2Fallback implements FeignClient2 {
@Override
public String findServiceInfoFromEurekaByServiceName(String serviceName) {
return "haha";
}
}
4、使用的配置类
@Configuration
public class Configuration2 {
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "a123");
} @Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}
可以看到这里主要增加了feignBuilder创建
示例三、 回退触发器的原因fallbackFactory属性
参考代码:
1、基本配置略
2、配置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的一个升级版
3、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;
}
};
}
}
4、UserFeignClientWithFactory设置
public interface UserFeignClientWithFactory extends UserFeignClient {
}
0503-Hystrix保护应用-feign的hystrix支持的更多相关文章
- SpringCloud Feign对Hystrix(断路由)的支持
		
第一步:首先开启Feign对Hystrix的支持,在properties文件中添加以下配置: feign.hystrix.enabled=true. 第二步:在上一篇Feign的基础上添加Hystri ...
 - Feign  Ribbon Hystrix 三者关系 |  史上最全, 深度解析
		
史上最全: Feign Ribbon Hystrix 三者关系 | 深度解析 疯狂创客圈 Java 分布式聊天室[ 亿级流量]实战系列之 -25[ 博客园 总入口 ] 前言 疯狂创客圈(笔者尼恩创建的 ...
 - 在dropwizard中使用feign,使用hystrix
		
前言 用惯了spring全家桶之后,试试dropwizard的Hello World也别有一帆风味.为了增强对外访问API的能力,需要引入open feign.这里简单在dropwizard中使用fe ...
 - Feign 与 Hystrix
		
Feign 与 Hystrix Feign是一个声明式的web服务客户端,它使得web服务调用非常的简单,当我们使用Feign时,Spring Cloud 整合了Ribbon和Eureka,从而为我们 ...
 - Feign使用Hystrix
		
Feign使用Hystrix开发步骤 1.导入依赖spring-cloud-starter-hystrix 2.消费启动类开启@EnableCircuitBreaker 3.配置yml文件feign. ...
 - spring cloud: Hystrix(四):feign类似于hystrix的断容器功能:fallback
		
spring cloud: Hystrix(四):feign使用hystrix @FeignClient支持回退的概念:fallback方法,这里有点类似于:@HystrixCommand(fallb ...
 - Spring Cloud(Dalston.SR5)--Feign 与 Hystrix 断路器整合
		
创建项目 要使 Feign 与 Hystrix 进行整合,我们需要增加 Feign 和 Hystrix 的依赖,修改 POM.xml 中增加以下依赖项如下: <?xmlversion=" ...
 - springcloud微服务实战:Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin
		
相信现在已经有很多小伙伴已经或者准备使用springcloud微服务了,接下来为大家搭建一个微服务框架,后期可以自己进行扩展.会提供一个小案例: 服务提供者和服务消费者 ,消费者会调用提供者的服务,新 ...
 - springcloud(九)-Feign使用Hystrix
		
前言 上一篇我们使用注解@HystrixCommond的fallbackMethod属性实现回退.然而,Feign是以接口形式工作的,它没有方法体,上一篇讲解的方式显然不适用于Feign. 那么Fei ...
 
随机推荐
- maven下载、配置和安装
			
Maven简介 #Apache Maven is a software project management and comprehension tool. Based on the concept ...
 - springmvc-servlet.xml
			
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
 - TCP/IP笔记(八)应用层协议
			
TCP/IP的应用层涵盖了OSI参考模型中第5.第6.第7层的所有功能,不仅包含了管理通信连接的会话层功能.转换数据格式的标识层功能,还包括与对端主机交互的应用层功能在内的所有功能. 利用网络的应用程 ...
 - 剖析top命令显示的VIRT RES SHR值
			
http://yalung929.blog.163.com/blog/static/203898225201212981731971/ http://www.fuzhijie.me/?p=741 引 ...
 - 用Eclipse的tomcat插件启动tomcat时报错:
			
用Eclipse的tomcat插件启动tomcat时报错: FATAL ERROR in native method: JDWP No transports initialized, jvmtiErr ...
 - thinkphp  从服务器拉取下来  验证码失效
			
public function verify(){ ob_end_clean();//加入 $verify = new \Think\Verify(); $verify->entry(1); }
 - WebAPI实现移动端上传头像接口
			
测试时可以直接使用PostMan模拟发送请求 /// <summary> /// 手机端上传头像接口 /// </summary> /// <param name=&qu ...
 - WPFLoading遮层罩
			
一直想实现这么个功能来着,所以去网上搜了资料,复杂的看不懂,后来挑了一个最简单的,复用了这位大神的很多代码(大神看到了别打脸).这位大神是用UserControl,使用时则是调用用户控件中的方法.之前 ...
 - 广义高斯分布(GGD)
			
广义高斯分布(GGD)-Generalized Gaussian Distribution 广义高斯分布及其在图像去噪的应用_百度文库 https://wenku.baidu.com/view/2b8 ...
 - CGContextRef用法
			
本文转载至 http://blog.csdn.net/perfect_promise/article/details/7660220 quartz 是主要的描画接口,支持基于路径的描画. 抗锯齿渲染. ...