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 ...
随机推荐
- jsp中判断对象是否存在
<!-- 如果user对象存在,则显示用户名,如果不存在,则显示空值--> <input type="text" id="userName" ...
- oracle分区的名称和值要一致
名称是01,后面的值也必须是02,不能是前面的是1,后面的是02,被这个问题困扰了好久.
- redis数据类型[string 、list 、 set 、sorted set 、hash]
1. Keys redis本质上一个key-value db,所以我们首先来看看他的key. 首先key也是字符串类型,但是key中不能包括边界字符:由于key不是binary safe的字符串, ...
- python -> lambda与def的差别
lambda能够定义一个匿名函数.而def定义的函数必须有一个名字. 这应该是lambda与def两者最大的差别. 与Javascript不同的是,python中匿名函数与非匿名函数须要使用不同的语法 ...
- 常见sql 写法总结
关于如何获取1对多数据中最大条数据的写法 例子: LEFT JOIN ( SELECT * FROM table AS n1 WHERE n1.ID IN ( SELECT MAX(id) FROM ...
- 【SVM】清晰明了的理论文章
http://www.cnblogs.com/jerrylead/archive/2011/03/13/1982639.html 松弛变量和惩罚因子: http://blog.csdn.net/yan ...
- Ubuntu右键添加:open in terminal
1.安装软件nautilus-open-terminal sudo apt-get install nautilus-open-terminal 2.重新加载文件管理器 nautilus -q 重新打 ...
- EF 更新操作 lambda解释+=
我曾写过一个EF批量更新.删除的博客,后来操作的过程中经常遇到更新字段,但是要在原来的基础上计算的情况,我就先去获取一遍数据然后再计算,最后再去更新,显然这个操作是很复杂的 var guest = d ...
- iOS 7 计算字符串高度
- (float)width:(NSString *)str font:(UIFont *)font { NSDictionary *attribute = @{NSFontAttributeName ...
- Canvas-三角函数曲线图
以本图为例,要做这张图,需要一些数学知识(三角函数sin,cos),有canvas的基础知识 Html <!DOCTYPE html> <html> <head> ...