一、概述

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的支持

参考代码:https://github.com/bjlhx15/spring-cloud/tree/master/microservice-comsumer-movie-feign-customizing-without-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支持的更多相关文章

  1. SpringCloud Feign对Hystrix(断路由)的支持

    第一步:首先开启Feign对Hystrix的支持,在properties文件中添加以下配置: feign.hystrix.enabled=true. 第二步:在上一篇Feign的基础上添加Hystri ...

  2. Feign Ribbon Hystrix 三者关系 | 史上最全, 深度解析

    史上最全: Feign Ribbon Hystrix 三者关系 | 深度解析 疯狂创客圈 Java 分布式聊天室[ 亿级流量]实战系列之 -25[ 博客园 总入口 ] 前言 疯狂创客圈(笔者尼恩创建的 ...

  3. 在dropwizard中使用feign,使用hystrix

    前言 用惯了spring全家桶之后,试试dropwizard的Hello World也别有一帆风味.为了增强对外访问API的能力,需要引入open feign.这里简单在dropwizard中使用fe ...

  4. Feign 与 Hystrix

    Feign 与 Hystrix Feign是一个声明式的web服务客户端,它使得web服务调用非常的简单,当我们使用Feign时,Spring Cloud 整合了Ribbon和Eureka,从而为我们 ...

  5. Feign使用Hystrix

    Feign使用Hystrix开发步骤 1.导入依赖spring-cloud-starter-hystrix 2.消费启动类开启@EnableCircuitBreaker 3.配置yml文件feign. ...

  6. spring cloud: Hystrix(四):feign类似于hystrix的断容器功能:fallback

    spring cloud: Hystrix(四):feign使用hystrix @FeignClient支持回退的概念:fallback方法,这里有点类似于:@HystrixCommand(fallb ...

  7. Spring Cloud(Dalston.SR5)--Feign 与 Hystrix 断路器整合

    创建项目 要使 Feign 与 Hystrix 进行整合,我们需要增加 Feign 和 Hystrix 的依赖,修改 POM.xml 中增加以下依赖项如下: <?xmlversion=" ...

  8. springcloud微服务实战:Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin

    相信现在已经有很多小伙伴已经或者准备使用springcloud微服务了,接下来为大家搭建一个微服务框架,后期可以自己进行扩展.会提供一个小案例: 服务提供者和服务消费者 ,消费者会调用提供者的服务,新 ...

  9. springcloud(九)-Feign使用Hystrix

    前言 上一篇我们使用注解@HystrixCommond的fallbackMethod属性实现回退.然而,Feign是以接口形式工作的,它没有方法体,上一篇讲解的方式显然不适用于Feign. 那么Fei ...

随机推荐

  1. [转]C/C++中volatile关键字详解

    http://www.cnblogs.com/yc_sunniwell/archive/2010/07/14/1777432.html

  2. flutter开发目录

    1>环境 2>设计 3>登录 4>主页面 5>主页面明细 6>详情 7>商品明细 8>购物车 9>订单页 10>个人关于 11>搜索页

  3. android webview处理h5打开本地文件浏览器的功能

    这周遇到一个比较棘手的问题,需要在android上边集成h5页面,并且在h5页面上,需要用户能够上传android本地的照片,一开始我以为webview会自动处理掉的,因此没太留意,当真正集成时,才发 ...

  4. Java WEB 之页面间传递特殊字符

    本文是学习网络上的文章时的总结以及自己的一点实践.感谢大家无私的分享. 昨天在做项目的时候,有一个页面间传递特殊字符的需求,查了一些资料.如今将自己的经验写出来. 首先.在前台编码 var fckPu ...

  5. 【Raspberry Pi】DHT11 温度湿度传感器数据读取

    时序图参考厂家说明书:DHT11数字湿温度传感器的原理和应用范例 四个阵脚连接:VCC接3.3伏电源,Dout接GPIO口,我接的是物理12针脚,NC留空,GND接地. 波折1:电阻被错接进了VCC, ...

  6. Java将视频转为缩略图--ffmpeg

    Java生成视频缩略图 对于上传视频生成缩略图使用的是ffmpeg进行生成的. 自己在网上找了如何进行编译ffmpeg的方法 但是感觉太复杂了 就到csdn上找到了编译好的ffmpeg文件 体会到ff ...

  7. TaoKeeper

    基于zookeeper的监控管理工具taokeeper,由淘宝团队开源的zk管理中间件: 按照taokeeper官方说明 http://jm-blog.aliapp.com/?p=1450 下载tao ...

  8. python入门(三):分支、循环、函数

    1.分支 if循环格式:if condition_1: statement_block_1elif condition_2: statement_block_2else: statement_bloc ...

  9. <转载> C++笔试、面试笔记

    这些东西有点烦,有点无聊.如果要去C++面试就看看吧.几年前网上搜索的.刚才看到,就整理一下,里面有些被我改了,感觉之前说的不对或不完善. 1.求下面函数的返回值( 微软) int func(x)  ...

  10. poj 1322 Chocolate (概率dp)

    ///有c种不同颜色的巧克力.一个个的取.当发现有同样的颜色的就吃掉.去了n个后.到最后还剩m个的概率 ///dp[i][j]表示取了i个还剩j个的概率 ///当m+n为奇时,概率为0 # inclu ...