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 ...
随机推荐
- Spring中的IOC
在学习spring的时候,最常听到的词应该就是IOC和AOP了,以下,我从我的角度再次理解一下Spring里的IOC和AOP. IOC简单介绍 IoC(InversionofControl):IoC就 ...
- wget命令 -c断点续传
wget -O wordpress.zip http://www.linuxde.net/download.aspx?id=1080 下载文件在指定位置并进行重命名 -O file - ...
- JDK8集合的便捷操作
JDK8新特性,stream相关操作.把集合转换成stream,再对其进行相关操作,加上lambada表达式. demo: List<String> list = Arrays.asLis ...
- GridLayout 可使容器中的各个组件呈网格状布局
GridLayout 可使容器中的各个组件呈网格状布局,平局占据容器的空间,即使容器的大小发生变化,每个组件还是平均占据容器的空间. 和FlowLayout一样,GridLayout也是按照从上到下, ...
- PHP 清除HTML代码、空格、回车换行符的函数
function DeleteHtml($str) { $str = trim($str); $str = strip_tags($str,""); $str = ereg_rep ...
- Java 反射机制[Field反射]
Java 反射机制[Field反射] 1. 反射概念及功能 反射就是把Java类中的各种成分映射成对应的Java类.比如一个Java类中用一个Class类的对象来表示. 一个类中的组成部分分为成员变 ...
- js压缩 uglify(2)
一.故事总有其背景 年末将至,很多闲适的时间,于是刷刷微博,接触各种纷杂的信息——美其名曰“学习”.运气不错,遇到了一个新名词,uglifyjs. 据说是用来压缩JS文件的,据说还能优化JS,据说是基 ...
- Oracle 常用性能监控SQL语句
1. --查看表锁 SELECT * FROM SYS.V_$SQLAREA WHERE DISK_READS > 100; 2. --监控事例的等待 SELECT EVEN ...
- 一站式WPF--依赖属性(DependencyProperty)二
书接上文,前篇文章介绍了依赖属性的原理和实现了一个简单的DependencyProperty(DP),这篇文章主要探讨一下如何使用DP以及有哪些需要注意的地方. 回顾 依赖属性是由Dependency ...
- .NET中的枚举用法浅析
本文简单分析了.NET中的枚举用法.分享给大家供大家参考.具体分析如下: 我理解的枚举就是编程中约定的一个“可选值”:例如QQ的在线状态,分别有 在线,Q我吧,隐身,忙碌等等...我觉得这就是一 ...