资讯专栏INFORMATION COLUMN

翻译:Hystrix - How To Use

acrazing / 1571人阅读

摘要:转载请注明出处翻译下面的代码展示了版的查看源码的同等实现如下可以通过调用方法实现同步执行示例如下测试如下不提供同步执行方法但是如果确定其只会产生一个值那么也可以用如下方式实现如果实际上产生了多个值上述的代码将会抛出可以通过调用方法实现异步

转载请注明出处: 翻译:Hystrix - How To Use

Hello World!

下面的代码展示了HystrixCommand版的Hello World:

</>复制代码

  1. public class CommandHelloWorld extends HystrixCommand {
  2. private final String name;
  3. public CommandHelloWorld(String name) {
  4. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  5. this.name = name;
  6. }
  7. @Override
  8. protected String run() {
  9. // a real example would do work like a network call here
  10. return "Hello " + name + "!";
  11. }
  12. }

查看源码

HystrixObservableCommand的同等实现如下:

</>复制代码

  1. public class CommandHelloWorld extends HystrixObservableCommand {
  2. private final String name;
  3. public CommandHelloWorld(String name) {
  4. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  5. this.name = name;
  6. }
  7. @Override
  8. protected Observable construct() {
  9. return Observable.create(new Observable.OnSubscribe() {
  10. @Override
  11. public void call(Subscriber observer) {
  12. try {
  13. if (!observer.isUnsubscribed()) {
  14. // a real example would do work like a network call here
  15. observer.onNext("Hello");
  16. observer.onNext(name + "!");
  17. observer.onCompleted();
  18. }
  19. } catch (Exception e) {
  20. observer.onError(e);
  21. }
  22. }
  23. } ).subscribeOn(Schedulers.io());
  24. }
  25. }
Synchronous Execution

可以通过调用HystrixCommand.execute()方法实现同步执行, 示例如下:

</>复制代码

  1. String s = new CommandHelloWorld("World").execute();

测试如下:

</>复制代码

  1. @Test
  2. public void testSynchronous() {
  3. assertEquals("Hello World!", new CommandHelloWorld("World").execute());
  4. assertEquals("Hello Bob!", new CommandHelloWorld("Bob").execute());
  5. }

HystrixObservableCommand不提供同步执行方法, 但是如果确定其只会产生一个值, 那么也可以用如下方式实现:

HystrixObservableCommand.observe().observe().toBlocking().toFuture().get()

HystrixObservableCommand.toObservable().observe().toBlocking().toFuture().get()

如果实际上产生了多个值, 上述的代码将会抛出java.lang.IllegalArgumentException: Sequence contains too many elements.

Asynchronous Execution

可以通过调用HystrixCommand.queue()方法实现异步执行, 示例如下:

</>复制代码

  1. Future fs = new CommandHelloWorld("World").queue();

此时可以通过Future.get()方法获取command执行结果:

</>复制代码

  1. String s = fs.get();

测试代码如下:

</>复制代码

  1. @Test
  2. public void testAsynchronous1() throws Exception {
  3. assertEquals("Hello World!", new CommandHelloWorld("World").queue().get());
  4. assertEquals("Hello Bob!", new CommandHelloWorld("Bob").queue().get());
  5. }
  6. @Test
  7. public void testAsynchronous2() throws Exception {
  8. Future fWorld = new CommandHelloWorld("World").queue();
  9. Future fBob = new CommandHelloWorld("Bob").queue();
  10. assertEquals("Hello World!", fWorld.get());
  11. assertEquals("Hello Bob!", fBob.get());
  12. }

下面的两种实现是等价的:

</>复制代码

  1. String s1 = new CommandHelloWorld("World").execute();
  2. String s2 = new CommandHelloWorld("World").queue().get();

HystrixObservableCommand不提供queue方法, 但是如果确定其只会产生一个值, 那么也可以用如下方式实现:

HystrixObservableCommand.observe().observe().toBlocking().toFuture()

HystrixObservableCommand.toObservable().observe().toBlocking().toFuture()

如果实际上产生了多个值, 上述的代码将会抛出java.lang.IllegalArgumentException: Sequence contains too many elements.

Reactive Execution

你也可以将HystrixCommand当做一个可观察对象(Observable)来观察(Observe)其产生的结果, 可以使用以下任意一个方法实现:

observe(): 一旦调用该方法, 请求将立即开始执行, 其利用ReplaySubject特性可以保证不会丢失任何command产生的结果, 即使结果在你订阅之前产生的也不会丢失.

toObservable(): 调用该方法后不会立即执行请求, 而是当有订阅者订阅时才会执行.

</>复制代码

  1. Observable ho = new CommandHelloWorld("World").observe();
  2. // or Observable co = new CommandHelloWorld("World").toObservable();

然后你可以通过订阅到这个Observable来取得command产生的结果:

</>复制代码

  1. ho.subscribe(new Action1() {
  2. @Override
  3. public void call(String s) {
  4. // value emitted here
  5. }
  6. });

测试如下:

</>复制代码

  1. @Test
  2. public void testObservable() throws Exception {
  3. Observable fWorld = new CommandHelloWorld("World").observe();
  4. Observable fBob = new CommandHelloWorld("Bob").observe();
  5. // blocking
  6. assertEquals("Hello World!", fWorld.toBlockingObservable().single());
  7. assertEquals("Hello Bob!", fBob.toBlockingObservable().single());
  8. // non-blocking
  9. // - this is a verbose anonymous inner-class approach and doesn"t do assertions
  10. fWorld.subscribe(new Observer() {
  11. @Override
  12. public void onCompleted() {
  13. // nothing needed here
  14. }
  15. @Override
  16. public void onError(Throwable e) {
  17. e.printStackTrace();
  18. }
  19. @Override
  20. public void onNext(String v) {
  21. System.out.println("onNext: " + v);
  22. }
  23. });
  24. // non-blocking
  25. // - also verbose anonymous inner-class
  26. // - ignore errors and onCompleted signal
  27. fBob.subscribe(new Action1() {
  28. @Override
  29. public void call(String v) {
  30. System.out.println("onNext: " + v);
  31. }
  32. });
  33. }

使用Java 8的Lambda表达式可以使代码更简洁:

</>复制代码

  1. fWorld.subscribe((v) -> {
  2. System.out.println("onNext: " + v);
  3. })
  4. // - or while also including error handling
  5. fWorld.subscribe((v) -> {
  6. System.out.println("onNext: " + v);
  7. }, (exception) -> {
  8. exception.printStackTrace();
  9. })

关于Observable的信息可以在这里查阅

Reactive Commands

相比将HystrixCommand使用上述方法转换成一个Observable, 你也可以选择创建一个HystrixObservableCommand对象. HystrixObservableCommand包装的Observable允许产生多个结果(译者注: Subscriber.onNext可以调用多次), 而HystrixCommand即使转换成了Observable也只能产生一个结果.

使用HystrixObservableCommnad时, 你需要重载construct方法来实现你的业务逻辑, 而不是重载run方法, contruct方法将会返回你需要包装的Observable.

使用下面任意一个方法可以从HystrixObservableCommand中获取Observable对象:

observe(): 一旦调用该方法, 请求将立即开始执行, 其利用ReplaySubject特性可以保证不会丢失任何command产生的结果, 即使结果在你订阅之前产生的也不会丢失.

toObservable(): 调用该方法后不会立即执行请求, 而是当有订阅者订阅时才会执行.

Fallback

大多数情况下, 我们都希望command在执行失败时能够有一个候选方法来处理, 如: 返回一个默认值或执行其他失败处理逻辑, 除了以下几个情况:

执行写操作的command: 当command的目标是执行写操作而不是读操作, 那么通常需要将写操作失败的错误交给调用者处理.

批处理系统/离线计算: 如果command的目标是做一些离线计算、生成报表、填充缓存等, 那么同样应该将失败交给调用者处理.

无论command是否实现了getFallback()方法, command执行失败时, Hystrix的状态和断路器(circuit-breaker)的状态/指标都会进行更新.

HystrixCommand可以通过实现getFallback()方法来实现降级处理, run()方法异常、执行超时、线程池或信号量已满拒绝提供服务、断路器短路时, 都会调用getFallback():

</>复制代码

  1. public class CommandHelloFailure extends HystrixCommand {
  2. private final String name;
  3. public CommandHelloFailure(String name) {
  4. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  5. this.name = name;
  6. }
  7. @Override
  8. protected String run() {
  9. throw new RuntimeException("this command always fails");
  10. }
  11. @Override
  12. protected String getFallback() {
  13. return "Hello Failure " + name + "!";
  14. }
  15. }

查看源码

这个命令的run()方法总是会执行失败, 但是调用者总是能收到getFallback()方法返回的值, 而不是收到一个异常:

</>复制代码

  1. @Test
  2. public void testSynchronous() {
  3. assertEquals("Hello Failure World!", new CommandHelloFailure("World").execute());
  4. assertEquals("Hello Failure Bob!", new CommandHelloFailure("Bob").execute());
  5. }

HystrixObservableCommand可以通过重载resumeWithFallback方法实现原Observable执行失败时返回回另一个Observable, 需要注意的是, 原Observable有可能在发出多个结果之后才出现错误, 因此在fallback实现的逻辑中不应该假设订阅者只会收到失败逻辑中发出的结果.

Hystrix内部使用了RxJavaonErrorResumeNext操作符来实现Observable之间的无缝转移.

Error Propagation

HystrixBadRequestException异常外, run方法中抛出的所有异常都会被认为是执行失败且会触发getFallback()方法和断路器的逻辑.

你可以在HystrixBadRequestException中包装想要抛出的异常, 然后通过getCause()方法获取. HystrixBadRequestException使用在不应该被错误指标(failure metrics)统计和不应该触发getFallback()方法的场景, 例如报告参数不合法或者非系统异常等.

对于HystrixObservableCommand, 不可恢复的错误都会在通过onError方法通知, 并通过获取用户实现的resumeWithFallback()方法返回的Observable来完成回退机制.

执行异常类型
Failure Type Exception class Exception.cause
FAILURE HystrixRuntimeException underlying exception(user-controlled)
TIMEOUT HystrixRuntimeException j.u.c.TimeoutException
SHORT_CIRCUITED HystrixRuntimeException j.l.RuntimeException
THREAD_POOL_REJECTED HystrixRuntimeException j.u.c.RejectedExecutionException
SEMAPHORE_REJECTED HystrixRuntimeException j.l.RuntimeException
BAD_REQUEST HystrixBadRequestException underlying exception(user-controller)
Command Name

默认的command name是从类名中派生的:

</>复制代码

  1. getClass().getSimpleName()

可以通过HystrixCommandHystrixObservableCommand的构造器来指定command name:

</>复制代码

  1. public CommandHelloWorld(String name) {
  2. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
  3. .andCommandKey(HystrixCommandKey.Factory.asKey("HelloWorld")));
  4. this.name = name;
  5. }

可以通过如下方式来重用Setter:

</>复制代码

  1. private static final Setter cachedSetter =
  2. Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
  3. .andCommandKey(HystrixCommandKey.Factory.asKey("HelloWorld"));
  4. public CommandHelloWorld(String name) {
  5. super(cachedSetter);
  6. this.name = name;
  7. }

HystrixCommandKey是一个接口, 因此可以将其实现为一个枚举或者常规的类, 但是它已经内置了一个Factory类来构建帮助构建内部实例, 使用方式如下:

</>复制代码

  1. HystrixCommandKey.Factory.asKey("Hello World");
Command Group

Hystrix使用command group来为分组, 分组信息主要用于报告、警报、仪表盘上显示, 或者是标识团队/库的拥有者.

默认情况下, 除非已经用这个名字定义了一个信号量, 否则 Hystrix将使用这个名称来定义command的线程池.

HystrixCommandGroupKey是一个接口, 因此可以将其实现为一个枚举或者常规的类, 但是它已经内置了一个Factory类来构建帮助构建内部实例, 使用方式如下:

</>复制代码

  1. HystrixCommandGroupKey.Factory.asKey("Example Group")
Command Thread-pool

thread-pool key主要用于在监控、指标发布、缓存等类似场景中标识一个HystrixThreadPool, 一个HystrixCommand于其构造函数中传入的HystrixThreadPoolKey指定的HystrixThreadPool相关联, 如果未指定的话, 则使用HystrixCommandGroupKey来获取/创建HystrixThreadPool.

可以通过HystrixCommandHystrixObservableCommand的构造器来指定其值:

</>复制代码

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

HystrixCommandThreadPoolKey是一个接口, 因此可以将其实现为一个枚举或者常规的类, 但是它已经内置了一个Factory类来构建帮助构建内部实例, 使用方式如下:

</>复制代码

  1. HystrixThreadPoolKey.Factory.asKey("Hello World Pool")

使用HystrixThreadPoolKey而不是使用不同的HystrixCommandGroupKey的原因是: 可能会有多条command在逻辑功能上属于同一个组(group), 但是其中的某些command需要和其他command隔离开, 例如:

两条用于访问视频元数据的command

两条commandgroup name都是VideoMetadata

command A与资源#1互斥

command B与资源#2互斥

如果command A由于延迟等原因导致其所在的线程池资源耗尽, 不应该影响command B#2的执行, 因为他们访问的是不同的后端资源.

因此, 从逻辑上来说, 我们希望这两条command应该被分到同一个分组, 但是我们同样系统将这两条命令的执行隔离开来, 因此我们使用HystrixThreadPoolKey将其分配到不同的线程池.

Request Cache

可以通过实现HystrixCommandHystrixObservableCommandgetCacheKey()方法开启用对请求的缓存功能:

</>复制代码

  1. public class CommandUsingRequestCache extends HystrixCommand {
  2. private final int value;
  3. protected CommandUsingRequestCache(int value) {
  4. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  5. this.value = value;
  6. }
  7. @Override
  8. protected Boolean run() {
  9. return value == 0 || value % 2 == 0;
  10. }
  11. @Override
  12. protected String getCacheKey() {
  13. return String.valueOf(value);
  14. }
  15. }

由于该功能依赖于请求的上下文信息, 因此我们必须初始化一个HystrixRequestContext, 使用方式如下:

</>复制代码

  1. @Test
  2. public void testWithoutCacheHits() {
  3. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  4. try {
  5. assertTrue(new CommandUsingRequestCache(2).execute());
  6. assertFalse(new CommandUsingRequestCache(1).execute());
  7. assertTrue(new CommandUsingRequestCache(0).execute());
  8. assertTrue(new CommandUsingRequestCache(58672).execute());
  9. } finally {
  10. context.shutdown();
  11. }
  12. }

通常情况下, 上下文信息(HystrixRequestContext)应该在持有用户请求的ServletFilter或者其他拥有生命周期管理功能的类来初始化和关闭.

下面的例子展示了command如何从缓存中获取数据, 以及如何查询一个数据是否是从缓存中获取到的:

</>复制代码

  1. @Test
  2. public void testWithCacheHits() {
  3. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  4. try {
  5. CommandUsingRequestCache command2a = new CommandUsingRequestCache(2);
  6. CommandUsingRequestCache command2b = new CommandUsingRequestCache(2);
  7. assertTrue(command2a.execute());
  8. // this is the first time we"ve executed this command with
  9. // the value of "2" so it should not be from cache
  10. assertFalse(command2a.isResponseFromCache());
  11. assertTrue(command2b.execute());
  12. // this is the second time we"ve executed this command with
  13. // the same value so it should return from cache
  14. assertTrue(command2b.isResponseFromCache());
  15. } finally {
  16. context.shutdown();
  17. }
  18. // start a new request context
  19. context = HystrixRequestContext.initializeContext();
  20. try {
  21. CommandUsingRequestCache command3b = new CommandUsingRequestCache(2);
  22. assertTrue(command3b.execute());
  23. // this is a new request context so this
  24. // should not come from cache
  25. assertFalse(command3b.isResponseFromCache());
  26. } finally {
  27. context.shutdown();
  28. }
  29. }
Request Collapsing

请求合并可以用于将多条请求绑定到一起, 由同一个HystrixCommand实例执行.

collapser可以通过batch sizebatch创建以来的耗时来自动将请求合并执行.

Hystrix支持两个请求合并方式: 请求级的合并和全局级的合并. 默认是请求范围的合并, 可以在构造collapser时指定值.

请求级(request-scoped)的collapser只会合并每一个HystrixRequestContext中的请求, 而全局级(globally-scoped)的collapser则可以跨HystrixRequestContext合并请求. 因此, 如果你下游的依赖者无法再一个command中处理多个HystrixRequestContext的话, 那么你应该使用请求级的合并.

在Netflix, 我们只会使用请求级的合并, 因为我们当前所有的系统都是基于一个command对应一个HystrixRequestContext的设想下构建的. 因此, 当一个command使用不同的参数在一个请求中并发执行时, 合并是有效的.

下面的代码展示了如何实现请求级的HystrixCollapser:

</>复制代码

  1. public class CommandCollapserGetValueForKey extends HystrixCollapser, String, Integer> {
  2. private final Integer key;
  3. public CommandCollapserGetValueForKey(Integer key) {
  4. this.key = key;
  5. }
  6. @Override
  7. public Integer getRequestArgument() {
  8. return key;
  9. }
  10. @Override
  11. protected HystrixCommand> createCommand(final Collection> requests) {
  12. return new BatchCommand(requests);
  13. }
  14. @Override
  15. protected void mapResponseToRequests(List batchResponse, Collection> requests) {
  16. int count = 0;
  17. for (CollapsedRequest request : requests) {
  18. request.setResponse(batchResponse.get(count++));
  19. }
  20. }
  21. private static final class BatchCommand extends HystrixCommand> {
  22. private final Collection> requests;
  23. private BatchCommand(Collection> requests) {
  24. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
  25. .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueForKey")));
  26. this.requests = requests;
  27. }
  28. @Override
  29. protected List run() {
  30. ArrayList response = new ArrayList();
  31. for (CollapsedRequest request : requests) {
  32. // artificial response for each argument received in the batch
  33. response.add("ValueForKey: " + request.getArgument());
  34. }
  35. return response;
  36. }
  37. }
  38. }

下面的代码展示了如果使用collapser自动合并4个CommandCollapserGetValueForKey到一个HystrixCommand中执行:

</>复制代码

  1. @Test
  2. public void testCollapser() throws Exception {
  3. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  4. try {
  5. Future f1 = new CommandCollapserGetValueForKey(1).queue();
  6. Future f2 = new CommandCollapserGetValueForKey(2).queue();
  7. Future f3 = new CommandCollapserGetValueForKey(3).queue();
  8. Future f4 = new CommandCollapserGetValueForKey(4).queue();
  9. assertEquals("ValueForKey: 1", f1.get());
  10. assertEquals("ValueForKey: 2", f2.get());
  11. assertEquals("ValueForKey: 3", f3.get());
  12. assertEquals("ValueForKey: 4", f4.get());
  13. // assert that the batch command "GetValueForKey" was in fact
  14. // executed and that it executed only once
  15. assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size());
  16. HystrixCommand command = HystrixRequestLog.getCurrentRequest().getExecutedCommands().toArray(new HystrixCommand[1])[0];
  17. // assert the command is the one we"re expecting
  18. assertEquals("GetValueForKey", command.getCommandKey().name());
  19. // confirm that it was a COLLAPSED command execution
  20. assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
  21. // and that it was successful
  22. assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
  23. } finally {
  24. context.shutdown();
  25. }
  26. }
Request Context Setup

使用请求级的特性时(如: 请求缓存、请求合并、请求日志)你必须管理HystrixRequestContext的生命周期(或者实现HystrixConcurrencyStategy).

这意味着你必须在请求之前执行如下代码:

</>复制代码

  1. HystrixRequestContext context = HystrixRequestContext.initializeContext();

并在请求结束后执行如下代码:

</>复制代码

  1. context.shutdown();

在标准的Java web应用中, 你可以使用Setvlet Filter实现的如下的过滤器来管理:

</>复制代码

  1. public class HystrixRequestContextServletFilter implements Filter {
  2. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  3. throws IOException, ServletException {
  4. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  5. try {
  6. chain.doFilter(request, response);
  7. } finally {
  8. context.shutdown();
  9. }
  10. }
  11. }

可以在web.xml中加入如下代码实现对所有的请求都使用该过滤器:

</>复制代码

  1. HystrixRequestContextServletFilter
  2. HystrixRequestContextServletFilter
  3. com.netflix.hystrix.contrib.requestservlet.HystrixRequestContextServletFilter
  4. HystrixRequestContextServletFilter
  5. /*
Common Patterns

以下是HystrixCommandHystrixObservableCommand的一般用法和使用模式.

Fail Fast

最基本的使用是执行一条只做一件事情且没有实现回退方法的command, 这样的command在发生任何错误时都会抛出异常:

</>复制代码

  1. public class CommandThatFailsFast extends HystrixCommand {
  2. private final boolean throwException;
  3. public CommandThatFailsFast(boolean throwException) {
  4. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  5. this.throwException = throwException;
  6. }
  7. @Override
  8. protected String run() {
  9. if (throwException) {
  10. throw new RuntimeException("failure from CommandThatFailsFast");
  11. } else {
  12. return "success";
  13. }
  14. }

下面的代码演示了上述行为:

</>复制代码

  1. @Test
  2. public void testSuccess() {
  3. assertEquals("success", new CommandThatFailsFast(false).execute());
  4. }
  5. @Test
  6. public void testFailure() {
  7. try {
  8. new CommandThatFailsFast(true).execute();
  9. fail("we should have thrown an exception");
  10. } catch (HystrixRuntimeException e) {
  11. assertEquals("failure from CommandThatFailsFast", e.getCause().getMessage());
  12. e.printStackTrace();
  13. }
  14. }

HystrixObservableCommand需要重载resumeWithFallback()方法来实现同样的行为:

</>复制代码

  1. @Override
  2. protected Observable resumeWithFallback() {
  3. if (throwException) {
  4. return Observable.error(new Throwable("failure from CommandThatFailsFast"));
  5. } else {
  6. return Observable.just("success");
  7. }
  8. }
Fail Silent

静默失败等同于返回一个空的响应或者移除功能. 可以是返回null、空Map、空List, 或者其他类似的响应.

可以通过实现HystrixCommand.getFallback()方法实现该功能:

</>复制代码

  1. public class CommandThatFailsSilently extends HystrixCommand {
  2. private final boolean throwException;
  3. public CommandThatFailsSilently(boolean throwException) {
  4. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  5. this.throwException = throwException;
  6. }
  7. @Override
  8. protected String run() {
  9. if (throwException) {
  10. throw new RuntimeException("failure from CommandThatFailsFast");
  11. } else {
  12. return "success";
  13. }
  14. }
  15. @Override
  16. protected String getFallback() {
  17. return null;
  18. }
  19. }

</>复制代码

  1. @Test
  2. public void testSuccess() {
  3. assertEquals("success", new CommandThatFailsSilently(false).execute());
  4. }
  5. @Test
  6. public void testFailure() {
  7. try {
  8. assertEquals(null, new CommandThatFailsSilently(true).execute());
  9. } catch (HystrixRuntimeException e) {
  10. fail("we should not get an exception as we fail silently with a fallback");
  11. }
  12. }

或者返回一个空List的实现如下:

</>复制代码

  1. @Override
  2. protected List getFallback() {
  3. return Collections.emptyList();
  4. }

HystrixObservableCommand可以通过重载resumeWithFallback()方法实现同样的行为:

</>复制代码

  1. @Override
  2. protected Observable resumeWithFallback() {
  3. return Observable.empty();
  4. }
Fallback: Static

Fallback可以返回代码里设定的默认值, 这种方式可以通过默认行为来有效避免于静默失败带来影响.

例如, 如果一个应返回true/false的用户认证的command执行失败了, 那么其默认行为可以如下:

</>复制代码

  1. @Override
  2. protected Boolean getFallback() {
  3. return true;
  4. }

对于HystrixObservableCommand可以通过重载resumeWithFallback()方法实现同样的行为:

</>复制代码

  1. @Override
  2. protected Observable resumeWithFallback() {
  3. return Observable.just( true );
  4. }
Fallback: Stubbed

command返回的是一个包含多个字段的复合对象, 且该对象的一部分字段值可以通过其他请求状态获得, 另一部分状态可以通过设置默认值获得时, 你通常需要使用存根(stubbed)模式.

你可能可以从存根值(stubbed values)中得到适当的值的情况如下:

cookies

请求参数和请求头

当前失败请求的前一个服务请求的响应

fallback代码块内可以静态地获取请求范围内的存根(stubbed)值, 但是通常我们更推荐在构建command实例时注入这些值, 就像下面实例的代码中的countryCodeFromGeoLookup一样:

</>复制代码

  1. public class CommandWithStubbedFallback extends HystrixCommand {
  2. private final int customerId;
  3. private final String countryCodeFromGeoLookup;
  4. /**
  5. * @param customerId
  6. * The customerID to retrieve UserAccount for
  7. * @param countryCodeFromGeoLookup
  8. * The default country code from the HTTP request geo code lookup used for fallback.
  9. */
  10. protected CommandWithStubbedFallback(int customerId, String countryCodeFromGeoLookup) {
  11. super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
  12. this.customerId = customerId;
  13. this.countryCodeFromGeoLookup = countryCodeFromGeoLookup;
  14. }
  15. @Override
  16. protected UserAccount run() {
  17. // fetch UserAccount from remote service
  18. // return UserAccountClient.getAccount(customerId);
  19. throw new RuntimeException("forcing failure for example");
  20. }
  21. @Override
  22. protected UserAccount getFallback() {
  23. /**
  24. * Return stubbed fallback with some static defaults, placeholders,
  25. * and an injected value "countryCodeFromGeoLookup" that we"ll use
  26. * instead of what we would have retrieved from the remote service.
  27. */
  28. return new UserAccount(customerId, "Unknown Name",
  29. countryCodeFromGeoLookup, true, true, false);
  30. }
  31. public static class UserAccount {
  32. private final int customerId;
  33. private final String name;
  34. private final String countryCode;
  35. private final boolean isFeatureXPermitted;
  36. private final boolean isFeatureYPermitted;
  37. private final boolean isFeatureZPermitted;
  38. UserAccount(int customerId, String name, String countryCode,
  39. boolean isFeatureXPermitted,
  40. boolean isFeatureYPermitted,
  41. boolean isFeatureZPermitted) {
  42. this.customerId = customerId;
  43. this.name = name;
  44. this.countryCode = countryCode;
  45. this.isFeatureXPermitted = isFeatureXPermitted;
  46. this.isFeatureYPermitted = isFeatureYPermitted;
  47. this.isFeatureZPermitted = isFeatureZPermitted;
  48. }
  49. }
  50. }

下面的代码演示了上述行为:

</>复制代码

  1. @Test
  2. public void test() {
  3. CommandWithStubbedFallback command = new CommandWithStubbedFallback(1234, "ca");
  4. UserAccount account = command.execute();
  5. assertTrue(command.isFailedExecution());
  6. assertTrue(command.isResponseFromFallback());
  7. assertEquals(1234, account.customerId);
  8. assertEquals("ca", account.countryCode);
  9. assertEquals(true, account.isFeatureXPermitted);
  10. assertEquals(true, account.isFeatureYPermitted);
  11. assertEquals(false, account.isFeatureZPermitted);
  12. }

对于HystrixObservableCommand可以通过重载resumeWithFallback()方法实现同样的行为:

</>复制代码

  1. @Override
  2. protected Observable resumeWithFallback() {
  3. return Observable.just( new UserAccount(customerId, "Unknown Name",
  4. countryCodeFromGeoLookup, true, true, false) );
  5. }

如果你想要从Observable中发出多个值, 那么当失败发生时, 原本的Observable可能已经发出的一部分值, 此时你或许更希望能够只从fallback逻辑中发出另一部分未被发出的值, 下面的例子就展示了如何实现这一个目的: 它通过追踪原Observable发出的最后一个值来实现fallback逻辑中的Observable应该从什么地方继续发出存根值(stubbed value) :

</>复制代码

  1. @Override
  2. protected Observable construct() {
  3. return Observable.just(1, 2, 3)
  4. .concatWith(Observable. error(new RuntimeException("forced error")))
  5. .doOnNext(new Action1() {
  6. @Override
  7. public void call(Integer t1) {
  8. lastSeen = t1;
  9. }
  10. })
  11. .subscribeOn(Schedulers.computation());
  12. }
  13. @Override
  14. protected Observable resumeWithFallback() {
  15. if (lastSeen < 4) {
  16. return Observable.range(lastSeen + 1, 4 - lastSeen);
  17. } else {
  18. return Observable.empty();
  19. }
  20. }
Fallback: Cache via Network

有时后端的服务异常也会引起command执行失败, 此时我们也可以从缓存中(如: memcached)取得相关的数据.

由于在fallback的逻辑代码中访问网络可能会再次失败, 因此必须构建新的HystrixCommandHystrixObservableCommand来执行:

很重要的一点是执行fallback逻辑的command需要在一个不同的线程池中执行, 否则如果原command的延迟变高且其所在线程池已经满了的话, 执行fallback逻辑的command将无法在同一个线程池中执行.

下面的代码展示了CommandWithFallbackViaNetwork如何在getFallback()方法中执行FallbackViaNetwork.

注意, FallbackViaNetwork同样也具有回退机制, 这里通过返回null来实现fail silent.

FallbackViaNetwork默认会从HystrixCommandGroupKey中继承线程池的配置RemoteServiceX, 因此需要在其构造器中注入HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback")来使其在不同的线程池中执行.

这样, CommandWithFallbackViaNetwork会在名为RemoteServiceX的线程池中执行, 而FallbackViaNetwork会在名为RemoteServiceXFallback的线程池中执行.

</>复制代码

  1. public class CommandWithFallbackViaNetwork extends HystrixCommand {
  2. private final int id;
  3. protected CommandWithFallbackViaNetwork(int id) {
  4. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
  5. .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueCommand")));
  6. this.id = id;
  7. }
  8. @Override
  9. protected String run() {
  10. // RemoteServiceXClient.getValue(id);
  11. throw new RuntimeException("force failure for example");
  12. }
  13. @Override
  14. protected String getFallback() {
  15. return new FallbackViaNetwork(id).execute();
  16. }
  17. private static class FallbackViaNetwork extends HystrixCommand {
  18. private final int id;
  19. public FallbackViaNetwork(int id) {
  20. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceX"))
  21. .andCommandKey(HystrixCommandKey.Factory.asKey("GetValueFallbackCommand"))
  22. // use a different threadpool for the fallback command
  23. // so saturating the RemoteServiceX pool won"t prevent
  24. // fallbacks from executing
  25. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RemoteServiceXFallback")));
  26. this.id = id;
  27. }
  28. @Override
  29. protected String run() {
  30. MemCacheClient.getValue(id);
  31. }
  32. @Override
  33. protected String getFallback() {
  34. // the fallback also failed
  35. // so this fallback-of-a-fallback will
  36. // fail silently and return null
  37. return null;
  38. }
  39. }
  40. }
Primary + Secondary with Fallback

有些系统可能具有是以双系统模式搭建的 — 主从模式或主备模式.

有时从系统或备用系统会被认为是失败状态的一种, 仅在执行fallback逻辑是才使用它;这种场景和Cache via Network一节中描述的场景是一样的.

然而, 如果切换到从系统是一个很正常时, 例如发布新代码时(这是有状态的系统发布代码的一种方式), 此时每当切换到从系统使用时, 主系统都是处于不可用状态,断路器将会打开且发出警报.

这并不是我们期望发生的事, 这种狼来了式的警报可能会导致真正发生问题的时候我们却把它当成正常的误报而忽略了.

因此, 我们可以通过在其前面放置一个门面HystrixCommand(见下文), 将主/从系统的切换视为正常的、健康的状态.

主从HystrixCommand都是需要访问网络且实现了特定的业务逻辑, 因此其实现上应该是线程隔离的. 它们可能具有显著的性能差距(通常从系统是一个静态缓存), 因此将两个command隔离的另一个好处是可以针对性地调优.

你不需要将这两个command都公开发布, 只需要将它们隐藏在另一个由信号量隔离的HystrixCommand中(称之为门面HystrixCommand), 在这个command中去实现主系统还是从系统的调用选择. 只有当主从系统都失败了, 才会去执行这个门面commandfallback逻辑.

门面HystrixCommand可以使用信号量隔离的, 因为其业务逻辑仅仅是调用另外两个线程隔离的HystrixCommand, 它不涉及任何的网络访问、重试等容易出错的事, 因此没必要将这部分代码放到其他线程去执行.

</>复制代码

  1. public class CommandFacadeWithPrimarySecondary extends HystrixCommand {
  2. private final static DynamicBooleanProperty usePrimary = DynamicPropertyFactory.getInstance().getBooleanProperty("primarySecondary.usePrimary", true);
  3. private final int id;
  4. public CommandFacadeWithPrimarySecondary(int id) {
  5. super(Setter
  6. .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX"))
  7. .andCommandKey(HystrixCommandKey.Factory.asKey("PrimarySecondaryCommand"))
  8. .andCommandPropertiesDefaults(
  9. // we want to default to semaphore-isolation since this wraps
  10. // 2 others commands that are already thread isolated
  11. HystrixCommandProperties.Setter()
  12. .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
  13. this.id = id;
  14. }
  15. @Override
  16. protected String run() {
  17. if (usePrimary.get()) {
  18. return new PrimaryCommand(id).execute();
  19. } else {
  20. return new SecondaryCommand(id).execute();
  21. }
  22. }
  23. @Override
  24. protected String getFallback() {
  25. return "static-fallback-" + id;
  26. }
  27. @Override
  28. protected String getCacheKey() {
  29. return String.valueOf(id);
  30. }
  31. private static class PrimaryCommand extends HystrixCommand {
  32. private final int id;
  33. private PrimaryCommand(int id) {
  34. super(Setter
  35. .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX"))
  36. .andCommandKey(HystrixCommandKey.Factory.asKey("PrimaryCommand"))
  37. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("PrimaryCommand"))
  38. .andCommandPropertiesDefaults(
  39. // we default to a 600ms timeout for primary
  40. HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(600)));
  41. this.id = id;
  42. }
  43. @Override
  44. protected String run() {
  45. // perform expensive "primary" service call
  46. return "responseFromPrimary-" + id;
  47. }
  48. }
  49. private static class SecondaryCommand extends HystrixCommand {
  50. private final int id;
  51. private SecondaryCommand(int id) {
  52. super(Setter
  53. .withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX"))
  54. .andCommandKey(HystrixCommandKey.Factory.asKey("SecondaryCommand"))
  55. .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("SecondaryCommand"))
  56. .andCommandPropertiesDefaults(
  57. // we default to a 100ms timeout for secondary
  58. HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(100)));
  59. this.id = id;
  60. }
  61. @Override
  62. protected String run() {
  63. // perform fast "secondary" service call
  64. return "responseFromSecondary-" + id;
  65. }
  66. }
  67. public static class UnitTest {
  68. @Test
  69. public void testPrimary() {
  70. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  71. try {
  72. ConfigurationManager.getConfigInstance().setProperty("primarySecondary.usePrimary", true);
  73. assertEquals("responseFromPrimary-20", new CommandFacadeWithPrimarySecondary(20).execute());
  74. } finally {
  75. context.shutdown();
  76. ConfigurationManager.getConfigInstance().clear();
  77. }
  78. }
  79. @Test
  80. public void testSecondary() {
  81. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  82. try {
  83. ConfigurationManager.getConfigInstance().setProperty("primarySecondary.usePrimary", false);
  84. assertEquals("responseFromSecondary-20", new CommandFacadeWithPrimarySecondary(20).execute());
  85. } finally {
  86. context.shutdown();
  87. ConfigurationManager.getConfigInstance().clear();
  88. }
  89. }
  90. }
  91. }
Client Doesn"t Perform Network Access

当你使用HystrixCommand实现的业务逻辑不涉及到网络访问、对延迟敏感且无法接受多线程带来的开销时, 你需要设置executionIsolationStrategy)属性的值为ExecutionIsolationStrategy.SEMAPHORE, 此时Hystrix会使用信号量隔离代替线程隔离.

下面的代码展示了如何为command设置该属性(也可以在运行时动态改变这个属性的值):

</>复制代码

  1. public class CommandUsingSemaphoreIsolation extends HystrixCommand {
  2. private final int id;
  3. public CommandUsingSemaphoreIsolation(int id) {
  4. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
  5. // since we"re doing an in-memory cache lookup we choose SEMAPHORE isolation
  6. .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
  7. .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
  8. this.id = id;
  9. }
  10. @Override
  11. protected String run() {
  12. // a real implementation would retrieve data from in memory data structure
  13. return "ValueFromHashMap_" + id;
  14. }
  15. }
Get-Set-Get with Request Cache Invalidation

Get-Set-Get是指: Get请求的结果被缓存下来后, 另一个command对同一个资源发出了Set请求, 此时由Get请求缓存的结果应该失效, 避免随后的Get请求获取到过时的缓存结果, 此时可以通过调用HystrixRequestCache.clear())方法来使缓存失效.

</>复制代码

  1. public class CommandUsingRequestCacheInvalidation {
  2. /* represents a remote data store */
  3. private static volatile String prefixStoredOnRemoteDataStore = "ValueBeforeSet_";
  4. public static class GetterCommand extends HystrixCommand {
  5. private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("GetterCommand");
  6. private final int id;
  7. public GetterCommand(int id) {
  8. super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GetSetGet"))
  9. .andCommandKey(GETTER_KEY));
  10. this.id = id;
  11. }
  12. @Override
  13. protected String run() {
  14. return prefixStoredOnRemoteDataStore + id;
  15. }
  16. @Override
  17. protected String getCacheKey() {
  18. return String.valueOf(id);
  19. }
  20. /**
  21. * Allow the cache to be flushed for this object.
  22. *
  23. * @param id
  24. * argument that would normally be passed to the command
  25. */
  26. public static void flushCache(int id) {
  27. HystrixRequestCache.getInstance(GETTER_KEY,
  28. HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id));
  29. }
  30. }
  31. public static class SetterCommand extends HystrixCommand {
  32. private final int id;
  33. private final String prefix;
  34. public SetterCommand(int id, String prefix) {
  35. super(HystrixCommandGroupKey.Factory.asKey("GetSetGet"));
  36. this.id = id;
  37. this.prefix = prefix;
  38. }
  39. @Override
  40. protected Void run() {
  41. // persist the value against the datastore
  42. prefixStoredOnRemoteDataStore = prefix;
  43. // flush the cache
  44. GetterCommand.flushCache(id);
  45. // no return value
  46. return null;
  47. }
  48. }
  49. }

</>复制代码

  1. @Test
  2. public void getGetSetGet() {
  3. HystrixRequestContext context = HystrixRequestContext.initializeContext();
  4. try {
  5. assertEquals("ValueBeforeSet_1", new GetterCommand(1).execute());
  6. GetterCommand commandAgainstCache = new GetterCommand(1);
  7. assertEquals("ValueBeforeSet_1", commandAgainstCache.execute());
  8. // confirm it executed against cache the second time
  9. assertTrue(commandAgainstCache.isResponseFromCache());
  10. // set the new value
  11. new SetterCommand(1, "ValueAfterSet_").execute();
  12. // fetch it again
  13. GetterCommand commandAfterSet = new GetterCommand(1);
  14. // the getter should return with the new prefix, not the value from cache
  15. assertFalse(commandAfterSet.isResponseFromCache());
  16. assertEquals("ValueAfterSet_1", commandAfterSet.execute());
  17. } finally {
  18. context.shutdown();
  19. }
  20. }
  21. }
Migrating a Library to Hystrix

如果你要迁移一个已有的客户端库到Hystrix, 你应该将所有的服务方法(service methods)替换成HystrixCommand.

服务方法(service methods)转而调用HystrixCommand且不在包含任何额外的业务逻辑.

因此, 在迁移之前, 一个服务库可能是这样的:

迁移完成之后, 服务库的用户要能直接访问到HystrixCommand, 或者通过服务门面(service facade)的代理间接访问到HystrixCommand.

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73416.html

相关文章

  • Hystrix工作原理(官方文档翻译

    摘要:使用线程池的好处通过线程在自己的线程池中隔离的好处是该应用程序完全可以不受失控的客户端库的威胁。简而言之,由线程池提供的隔离功能可以使客户端库和子系统性能特性的不断变化和动态组合得到优雅的处理,而不会造成中断。 ​ 工作流程图 下面的流程图展示了当使用Hystrix的依赖请求,Hystrix是如何工作的。showImg(https://segmentfault.com/img/bV0...

    Lycheeee 评论0 收藏0
  • Hystrix基础入门和特性讲解

    摘要:断路器本身是一种开关装置,用于在电路上保护线路过载,当线路中有电器发生短路时,断路器能够及时的切断故障电路,防止发生过载发热甚至起火等严重后果。具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以及监控和配置等功能。 转载请注明出处 http://www.paraller.com 代码机制:熔断 & Fallback & 资源隔离 熔断 概念: 在微服务架构中,我们将系...

    dkzwm 评论0 收藏0
  • springboot+zipkin+docker实例

    摘要:脚本位置依赖内采样率,默认即如需测试时每次都看到则修改为,但对性能有影响,注意上线时修改为合理值运行查询参考规范推荐推荐谷歌的大规模分布式跟踪系统分布式服务的 zipkin-server pom io.zipkin zipkin-ui 1.39.3 or...

    Wuv1Up 评论0 收藏0
  • Netflix Hystrix断路器原理分析

    摘要:断路器原理断路器在和执行过程中起到至关重要的作用。其中通过来定义,每一个命令都需要有一个来标识,同时根据这个可以找到对应的断路器实例。一个啥都不做的断路器,它允许所有请求通过,并且断路器始终处于闭合状态断路器的另一个实现类。 断路器原理 断路器在HystrixCommand和HystrixObservableCommand执行过程中起到至关重要的作用。查看一下核心组件HystrixCi...

    Lemon_95 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<