maven引入

<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.13</version>
</dependency>

hello,world

  1. 继承HystrixCommand;
  2. HystrixCommandGroupKey是基类构造器必须的一个参数,可以实现接口来创建,也可以通过工厂方法HystrixCommandGroupKey.Factory.asKey(String)来创建;
  3. 实现run()方法;
  4. 调用
public class CommandHelloWorld extends HystrixCommand<String> {

    private final String name;

    public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
} @Override
protected String run() {
// a real example would do work like a network call here
return "Hello " + name + "!";
}
} @Test
public void testSynchronous() {
assertEquals("Hello World!", new CommandHelloWorld("World").execute();
}

execute/queue/observe

String s1 = new CommandHelloWorld("World").execute();

Future<String> fs = new CommandHelloWorld("World").queue();
String s2 = fs.get(); Observable<String> ho = new CommandHelloWorld("World").observe();
ho.subscribe(new Action1<String>() {
@Override
public void call(String s) {
// value emitted here
}
}); Observable<String> co = new CommandHelloWorld("World").toObservable();

observe() — returns a “hot” Observable that executes the command immediately, though because the Observable is filtered through a ReplaySubject you are not in danger of losing any items that it emits before you have a chance to subscribe

toObservable() — returns a “cold” Observable that won’t execute the command and begin emitting its results until you subscribe to the Observable

Fallback

public class CommandHelloFailure extends HystrixCommand<String> {

    private final String name;

    public CommandHelloFailure(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
} @Override
protected String run() {
throw new RuntimeException("this command always fails");
} @Override
protected String getFallback() {
return "Hello Failure " + name + "!";
}
}

Command Name & Command Group & Command Thread-Pool

public CommandHelloWorld(String name) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
.andCommandKey(HystrixCommandKey.Factory.asKey("HelloWorld"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("HelloWorldPool")));
this.name = name;
}

概念说明

  1. Command Group: Hystrix uses the command group key to group together commands such as for reporting, alerting, dashboards, or team/library ownership.
  2. Command Thread-Pool: The thread-pool key represents a HystrixThreadPool for monitoring, metrics publishing, caching, and other such uses. A HystrixCommand is associated with a single HystrixThreadPool as retrieved by the HystrixThreadPoolKey injected into it, or it defaults to one created using the HystrixCommandGroupKey it is created with.

缓存

通过实现getCacheKey()方法来开启缓存

public class CommandUsingRequestCache extends HystrixCommand<Boolean> {

    private final int value;

    protected CommandUsingRequestCache(int value) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.value = value;
} @Override
protected Boolean run() {
return value == 0 || value % 2 == 0;
} @Override
protected String getCacheKey() {
return String.valueOf(value);
}
}

请求合并

request-scoped: 同一个HystrixRequestContext

globally-scoped: 跨多个HystrixRequestContext

关于请求合并这篇通过HystrixCollapser合并请求提高应用吞吐量的例子比较好,正好利用请求合并并发挥es的mget的作用。转载于此。

    //利用hystrix合并请求
// scope:
// 合并作用域,默认是REQUEST,就是不会跨越多个请求会话的,只在当前用户请求中合并多次请求为批处理请求。这里改成GLOBAL,就是可以跨越request context,合并不同用户的请求为一次批处理请求。
// timerDelayInMilliseconds & maxRequestsInBatch:
// 表示合并请求的时间窗口为50ms,窗口时间内最多合并200个请求。默认值是10ms,合并请求数不限。
@HystrixCollapser(batchMethod = "mGetDataFromEs", scope = GLOBAL, collapserProperties = {
@HystrixProperty(name = "timerDelayInMilliseconds", value = "50"),
@HystrixProperty(name = "maxRequestsInBatch", value = "200"),
})
@Cacheable(value = "esRequestCache", cacheManager = "esRequestCacheManager", key = "#doc.index+':'+#doc.type+':'+#doc.id", unless = "#result == null || #result.size() ==0")
public List<RecommendItem> getDataFromEs3(EsDocGetRequest doc) {
return null;
} // fallbackMethod: 指定fallback方法
@HystrixCommand(fallbackMethod = "mGetDataFromEsFallback")
public List<List<RecommendItem>> mGetDataFromEs(List<EsDocGetRequest> docs) throws IOException {
logger.debug("================mGetDataFromEs==============");
List<List<RecommendItem>> datas = new ArrayList<>();
List<Doc> docList = new ArrayList<>();
for (EsDocGetRequest req : docs) {
docList.add(new Doc(req.getIndex(), req.getType(), req.getId()));
}
long start = System.currentTimeMillis();
JestResult result = jestClient.execute(new MultiGetExt.Builder.ByDoc(docList).build());
logger.info("============mGetDataFromEs cost time:{}", (System.currentTimeMillis() - start));
// assertTrue(result.getErrorMessage(), result.isSucceeded());
if (result.isSucceeded()) {
JsonArray actualDocs = result.getJsonObject().getAsJsonArray("docs");
for (int i = 0; i < docs.size(); i++) {
boolean hasError = actualDocs.get(i).getAsJsonObject().has("error");
boolean found = !hasError && actualDocs.get(i).getAsJsonObject().getAsJsonPrimitive("found").getAsBoolean();
if (found) {
EsRcmdResult esRcmdResult = gson.fromJson(actualDocs.get(i).getAsJsonObject().get("_source"), EsRcmdResult.class);
datas.add(esRcmdResult.getData());
} else {
datas.add(Collections.emptyList());
}
}
return datas;
} else {
throw new ServiceException(result.getErrorMessage());
} } public List<List<RecommendItem>> mGetDataFromEsFallback(List<EsDocGetRequest> docs) throws IOException {
logger.error("============mGetDataFromEs fallback=============");
return Collections.emptyList();
}

Request Context Setup

public class HystrixRequestContextServletFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
chain.doFilter(request, response);
} finally {
context.shutdown();
}
}
}

Common Patterns

In the following sections are common uses and patterns of use for HystrixCommand and HystrixObservableCommand.

Fail Fast

  1. has no fallback behivor
  2. throws HystrixRuntimeException
  3. 通过HystrixRuntimeException.getCause获取原始异常对象

Fail Silent

Failing silently is the equivalent of returning an empty response or removing functionality. It can be done by returning null, an empty Map, empty List, or other such responses.

@Override
protected String getFallback() {
return null;
} @Override
protected List<String> getFallback() {
return Collections.emptyList();
} // HystrixObservableCommand
@Override
protected Observable<String> resumeWithFallback() {
return Observable.empty();
}

Fallback: Static

在fallback方法里返回一个静态值

@Override
protected Boolean getFallback() {
return true;
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.just( true );
}

Falllback: Stubbed

You typically use a stubbed fallback when your command returns a compound object containing multiple fields, some of which can be determined from other request state while other fields are set to default values.

Fallback: Cache via Network

Dynamic Property

example:primary--secondary-with-fallback

// write
ConfigurationManager.getConfigInstance().setProperty("primarySecondary.usePrimary", true);
// read
DynamicBooleanProperty usePrimary = DynamicPropertyFactory.getInstance().getBooleanProperty("primarySecondary.usePrimary", true);

Properties Strategy

If you implement a custom HystrixPropertiesStrategy, this gives you full control over how properties are defined for the system.

The default implementation uses Archaius.

todo: 如何运行时变更配置?

HystrixPlugins.getInstance().registerPropertiesStrategy(null);?

hystrix-javanica

什么是ReactiveX

ReactiveX is a library for composing asynchronous and event-based programs by using observable sequences.

It extends the observer pattern to support sequences of data and/or events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety, concurrent data structures, and non-blocking I/O.

其他

  1. javadoc: HystrixRequestContext
  2. hystrix-request-servlet

Netflix Hystrix笔记的更多相关文章

  1. Netflix Hystrix - 快速入门

    Hystrix最初是由Netflix的API team研发的,用于提高API的弹性和性能,2012年在公司内部广受好评. 如果你的应用是一个单独的应用,那几乎不用在意断路的问题. 但在分布式环境中,各 ...

  2. 【spring cloud】子模块启动报错com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect

    spring cloud子模块启动报错 Caused by: java.lang.ClassNotFoundException: com.netflix.hystrix.contrib.javanic ...

  3. Spring Cloud Netflix Hystrix介绍和使用

    前面我们搭建了具有服务降级功能的Hystrix客户端,现在我们来详细了解下Hystrix的一些功能. Hystrix的意思是豪猪,大家都知道,就是长满刺的猪...实际上,它表明了该框架的主要功能:自我 ...

  4. java.lang.ClassNotFoundException: com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect

    添加这个依赖 <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystr ...

  5. springCloud学习3(Netflix Hystrix弹性客户端)

    springcloud 总集:https://www.tapme.top/blog/detail/2019-02-28-11-33 本次用到全部代码见文章最下方. 一.为什么要有客户端弹性模式   所 ...

  6. SpringCloud Netflix Hystrix

    Hystrix的一些概念 Hystrix是一个容错框架,可以有效停止服务依赖出故障造成的级联故障. 和eureka.ribbon.feign一样,也是Netflix家的开源框架,已被SpringClo ...

  7. Spring Cloud 系列之 Netflix Hystrix 服务容错

    什么是 Hystrix Hystrix 源自 Netflix 团队于 2011 年开始研发.2012年 Hystrix 不断发展和成熟,Netflix 内部的许多团队都采用了它.如今,每天在 Netf ...

  8. Spring Cloud 系列之 Netflix Hystrix 服务监控

    Actuator Hystrix 除了可以实现服务容错之外,还提供了近乎实时的监控功能,将服务执行结果和运行指标,请求数量成功数量等等这些状态通过 Actuator 进行收集,然后访问 /actuat ...

  9. SpringCloud系列之服务容错保护Netflix Hystrix

    1. 什么是雪崩效应? 微服务环境,各服务之间是经常相互依赖的,如果某个不可用,很容易引起连锁效应,造成整个系统的不可用,这种现象称为服务雪崩效应. 如图,引用国外网站的图例:https://www. ...

随机推荐

  1. .net 任务(Task)

    1. Task (任务): 很容易调用 ThreadPool.QueueUserWorkItem 实现异步操作,但是这个技术有许多 .net 引入Task类型来使用任务. 如下几种方式都是实现异步的方 ...

  2. 键盘控制背景边框平滑移动(jquery)

    今天同事让我看了一个动画效果,是由键盘控制背景边框平滑移动,我感觉挺cool,所以我自己也动手制作了一个.目的是为了锻炼自己,看自己是否也能在短时间内实现. 先上图: 一.html代码 <!DO ...

  3. IOS 6 自动布局 入门

    http://blog.csdn.net/itianyi/article/details/8535392

  4. Session概述

    session即HttpContext.Session 属性,命名空间System.Web 我们都知道,Cookie信息全部存放于客户端,Session则只是将一个ID存放在客户端做为与服务端验证的标 ...

  5. webapi之权限验证

    webapi之权限验证 一.概念: 二.demo: 1.登录时生成token: FormsAuthenticationTicket token = , account, DateTime.Now, D ...

  6. Tomcat源码(一):整体架构

    由于tomcat的组件较多,处理流程比较复杂 ,这里是 由浅到深来解释tomcat的整体架构 1.首先应该大致了解下tomcat的 /conf/server.xml  配置文件:在tomcat启动的时 ...

  7. HAOI2010 工厂选址

    题目链接:戳我 数组开小火葬场qwqwq 就是一个贪心吧.对于一个数,我们知道只有两种摆放方式.所以我们可以先都放到新的里面,然后做一下新的-原先的差,按照差从大到小排序,依次提取数值减去即可. 代码 ...

  8. linux和windows之间的文件压缩和解压缩以及^R的问题

    推荐大家使用zip压缩和解压,因为zip一般是linux系统自带: 一.zip和unzip 1. zip压缩 zip -r myfile.zip ./web 将当前目录里的web下的所有文件和文件夹全 ...

  9. 如何保证一个textfield输入最长的文字

    NSString *lang = [self.inputTextField.textInputMode primaryLanguage]; // 键盘输入模式 if ([lang isEqualToS ...

  10. C#中简单操作Mysql数据库

    以C#访问MySQL数据库,执行简单的CRUD. MySql.Data.dll是C#操作MySQL的驱动文件,是C#连接MySQL必要插件,使C#语言更简洁的操作MySQL数据库.可以用NuGet命令 ...