Hystrix: Latency and Fault Tolerance for Distributed Systems



com.netflix.hystrix
Class HystrixCommand<R>

java.lang.Object
  extended by com.netflix.hystrix.HystrixCommand<R>
Type Parameters:
R - the return type
All Implemented Interfaces:
HystrixExecutable<R>

@ThreadSafe
public abstract class HystrixCommand<R>
extends java.lang.Object
implements HystrixExecutable<R>

Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality.


Nested Class Summary
static class HystrixCommand.Setter
          Fluent interface for arguments to the HystrixCommand constructor.
 
Constructor Summary
protected HystrixCommand(HystrixCommand.Setter setter)
          Construct a HystrixCommand with defined HystrixCommand.Setter that allows injecting property and strategy overrides and other optional arguments.
protected HystrixCommand(HystrixCommandGroupKey group)
          Construct a HystrixCommand with defined HystrixCommandGroupKey.
 
Method Summary
 R execute()
          Used for synchronous execution of command.
protected  java.lang.String getCacheKey()
          Key to be used for request caching.
 HystrixCommandGroupKey getCommandGroup()
           
 HystrixCommandKey getCommandKey()
           
 java.util.List<HystrixEventType> getExecutionEvents()
          List of HystrixCommandEventType enums representing events that occurred during execution.
 int getExecutionTimeInMilliseconds()
          The execution time of this command instance in milliseconds, or -1 if not executed.
 java.lang.Throwable getFailedExecutionException()
          Get the Throwable/Exception thrown that caused the failure.
protected  R getFallback()
          If HystrixCommand.execute() or HystrixCommand.queue() fails in any way then this method will be invoked to provide an opportunity to return a fallback response.
 HystrixCommandMetrics getMetrics()
          The HystrixCommandMetrics associated with this HystrixCommand instance.
 HystrixCommandProperties getProperties()
          The HystrixCommandProperties associated with this HystrixCommand instance.
 HystrixThreadPoolKey getThreadPoolKey()
           
 boolean isCircuitBreakerOpen()
          Whether the 'circuit-breaker' is open meaning that execute() will immediately return the getFallback() response and not attempt a HystrixCommand execution.
 boolean isExecutedInThread()
          Whether the execution occurred in a separate thread.
 boolean isExecutionComplete()
          If this command has completed execution either successfully, via fallback or failure.
 boolean isFailedExecution()
          Whether the run() resulted in a failure (exception).
 boolean isResponseFromCache()
          Whether the response is from cache and run() was not invoked.
 boolean isResponseFromFallback()
          Whether the response received from was the result of some type of failure and getFallback() being called.
 boolean isResponseRejected()
          Whether the response received was a fallback as result of being rejected (from thread-pool or semaphore) and getFallback() being called.
 boolean isResponseShortCircuited()
          Whether the response received was a fallback as result of being short-circuited (meaning isCircuitBreakerOpen() == true) and getFallback() being called.
 boolean isResponseTimedOut()
          Whether the response received was the result of a timeout and getFallback() being called.
 boolean isSuccessfulExecution()
          Whether the response was returned successfully either by executing run() or from cache.
 java.util.concurrent.Future<R> queue()
          Used for asynchronous execution of command.
protected abstract  R run()
          Implement this method with code to be executed when HystrixCommand.execute() or HystrixCommand.queue() are invoked.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

HystrixCommand

protected HystrixCommand(HystrixCommandGroupKey group)
Construct a HystrixCommand with defined HystrixCommandGroupKey.

The HystrixCommandKey will be derived from the implementing class name.

Parameters:
group - HystrixCommandGroupKey used to group together multiple HystrixCommand objects.

The HystrixCommandGroupKey is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, common business purpose etc.


HystrixCommand

protected HystrixCommand(HystrixCommand.Setter setter)
Construct a HystrixCommand with defined HystrixCommand.Setter that allows injecting property and strategy overrides and other optional arguments.

NOTE: The HystrixCommandKey is used to associate a HystrixCommand with HystrixCircuitBreaker, HystrixCommandMetrics and other objects.

Do not create multiple HystrixCommand implementations with the same HystrixCommandKey but different injected default properties as the first instantiated will win.

Parameters:
setter - Fluent interface for constructor arguments
Method Detail

run

protected abstract R run()
                  throws java.lang.Exception
Implement this method with code to be executed when HystrixCommand.execute() or HystrixCommand.queue() are invoked.

Returns:
R response type
Throws:
java.lang.Exception - if command execution fails

getFallback

protected R getFallback()
If HystrixCommand.execute() or HystrixCommand.queue() fails in any way then this method will be invoked to provide an opportunity to return a fallback response.

This should do work that does not require network transport to produce.

In other words, this should be a static or cached result that can immediately be returned upon failure.

If network traffic is wanted for fallback (such as going to MemCache) then the fallback implementation should invoke another HystrixCommand instance that protects against that network access and possibly has another level of fallback that does not involve network access.

DEFAULT BEHAVIOR: It throws UnsupportedOperationException.

Returns:
R or throw UnsupportedOperationException if not implemented

getCommandGroup

public final HystrixCommandGroupKey getCommandGroup()
Returns:
HystrixCommandGroupKey used to group together multiple HystrixCommand objects.

The HystrixCommandGroupKey is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, common business purpose etc.


getCommandKey

public final HystrixCommandKey getCommandKey()
Returns:
HystrixCommandKey identifying this command instance for statistics, circuit-breaker, properties, etc.

getThreadPoolKey

public final HystrixThreadPoolKey getThreadPoolKey()
Returns:
HystrixThreadPoolKey identifying which thread-pool this command uses (when configured to run on separate threads via HystrixCommandProperties.executionIsolationStrategy()).

getMetrics

public final HystrixCommandMetrics getMetrics()
The HystrixCommandMetrics associated with this HystrixCommand instance.

Returns:
HystrixCommandMetrics

getProperties

public final HystrixCommandProperties getProperties()
The HystrixCommandProperties associated with this HystrixCommand instance.

Returns:
HystrixCommandProperties

execute

public final R execute()
Used for synchronous execution of command.

Specified by:
execute in interface HystrixExecutable<R>
Returns:
R Result of HystrixCommand.run() execution or a fallback from HystrixCommand.getFallback() if the command fails for any reason.
Throws:
HystrixRuntimeException - if a failure occurs and a fallback cannot be retrieved
HystrixBadRequestException - if invalid arguments or state were used representing a user failure, not a system failure

queue

public final java.util.concurrent.Future<R> queue()
Used for asynchronous execution of command.

This will queue up the command on the thread pool and return an Future to get the result once it completes.

NOTE: If configured to not run in a separate thread, this will have the same effect as HystrixCommand.execute() and will block.

We don't throw an exception but just flip to synchronous execution so code doesn't need to change in order to switch a command from running on a separate thread to the calling thread.

Specified by:
queue in interface HystrixExecutable<R>
Returns:
Future<R> Result of HystrixCommand.run() execution or a fallback from HystrixCommand.getFallback() if the command fails for any reason.
Throws:
HystrixRuntimeException - via Future.get() in Throwable.getCause() if a failure occurs and a fallback cannot be retrieved
HystrixBadRequestException - via Future.get() in Throwable.getCause() if invalid arguments or state were used representing a user failure, not a system failure

isCircuitBreakerOpen

public final boolean isCircuitBreakerOpen()
Whether the 'circuit-breaker' is open meaning that execute() will immediately return the getFallback() response and not attempt a HystrixCommand execution.

Returns:
boolean

isExecutionComplete

public final boolean isExecutionComplete()
If this command has completed execution either successfully, via fallback or failure.

Returns:
boolean

isExecutedInThread

public final boolean isExecutedInThread()
Whether the execution occurred in a separate thread.

This should be called only once execute()/queue()/fireOrForget() are called otherwise it will always return false.

This specifies if a thread execution actually occurred, not just if it is configured to be executed in a thread.

Returns:
boolean

isSuccessfulExecution

public final boolean isSuccessfulExecution()
Whether the response was returned successfully either by executing run() or from cache.

Returns:
boolean

isFailedExecution

public final boolean isFailedExecution()
Whether the run() resulted in a failure (exception).

Returns:
boolean

getFailedExecutionException

public final java.lang.Throwable getFailedExecutionException()
Get the Throwable/Exception thrown that caused the failure.

If isFailedExecution() == true then this would represent the Exception thrown by the run() method.

If isFailedExecution() == false then this would return null.

Returns:
Throwable or null

isResponseFromFallback

public final boolean isResponseFromFallback()
Whether the response received from was the result of some type of failure and getFallback() being called.

Returns:
boolean

isResponseTimedOut

public final boolean isResponseTimedOut()
Whether the response received was the result of a timeout and getFallback() being called.

Returns:
boolean

isResponseShortCircuited

public final boolean isResponseShortCircuited()
Whether the response received was a fallback as result of being short-circuited (meaning isCircuitBreakerOpen() == true) and getFallback() being called.

Returns:
boolean

isResponseFromCache

public final boolean isResponseFromCache()
Whether the response is from cache and run() was not invoked.

Returns:
boolean

isResponseRejected

public final boolean isResponseRejected()
Whether the response received was a fallback as result of being rejected (from thread-pool or semaphore) and getFallback() being called.

Returns:
boolean

getExecutionEvents

public final java.util.List<HystrixEventType> getExecutionEvents()
List of HystrixCommandEventType enums representing events that occurred during execution.

Examples of events are SUCCESS, FAILURE, TIMEOUT, and SHORT_CIRCUITED

Returns:
List<HystrixEventType>

getExecutionTimeInMilliseconds

public final int getExecutionTimeInMilliseconds()
The execution time of this command instance in milliseconds, or -1 if not executed.

Returns:
int

getCacheKey

protected java.lang.String getCacheKey()
Key to be used for request caching.

By default this returns null which means "do not cache".

To enable caching override this method and return a string key uniquely representing the state of a command instance.

If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache.

Returns:
cacheKey