# hystrix-javanica
Java language has a great advantages over other languages such as reflection and annotations.
All modern frameworks such as Spring, Hibernate, myBatis and etc. seek to use this advantages to the maximum.
The idea of introduction annotations in Hystrix is obvious solution for improvement. Currently using Hystrix involves writing a lot of code that is a barrier to rapid development. You likely be spending a lot of time on writing a Hystrix commands. Idea of the Javanica project is make easier using of Hystrix by the introduction of support annotations.
First of all in order to use hystrix-javanica you need to add hystrix-javanica dependency in your project.
Example for Maven:
```xml
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>x.y.z</version>
</dependency>
```
To implement AOP functionality in the project was used AspectJ library. If in your project already used AspectJ then you need to add hystrix aspect in aop.xml as below:
```xml
<aspects>
...
<aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
...
</aspects>
```
More about AspectJ configuration read [here] (http://www.eclipse.org/aspectj/doc/next/devguide/ltw-configuration.html)
If you use Spring AOP in your project then you need to add specific configuration using Spring AOP namespace in order to make Spring capable to manage aspects which were written using AspectJ and declare `HystrixCommandAspect` as Spring bean like below:
```xml
<aop:aspectj-autoproxy/>
<bean id="hystrixAspect" class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"></bean>
```
Or if you are using Spring code configuration:
```java
@Configuration
public class HystrixConfiguration {
@Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
}
```
It doesn't matter which approach you use to create proxies in Spring, javanica works fine with JDK and CGLIB proxies. If you use another framework for aop which supports AspectJ and uses other libs (Javassist for instance) to create proxies then let us know what lib you use to create proxies and we'll try to add support for this library in near future.
More about Spring AOP + AspectJ read [here] (http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html)
## Aspect weaving
Javanica supports two weaving modes: implementation and runtime. Load time weaving hasn't been tested but it should work. If you tried LTW mode and got any problems then raise javanica issue or create pull request with fix.
- CTW. To use CTW mode you need to use specific jar version: **hystrix-javanica-ctw-X.Y.Z** . This jar is assembled with aspects compiled with using [AJC](https://eclipse.org/aspectj/doc/next/devguide/ajc-ref.html) compiler. If you will try to use regular hystrix-javanica-X.Y.Z with CTW then you get ``` NoSuchMethodError aspectOf() ``` at runtime from building with iajc. Also, you need to start your app with using java property: ```-DWeavingMode=compile```.
**NOTE**: Javanica depends on aspectj library and uses internal features of aspectj and these features aren't provided as a part of open API thus it can change from version to version. Javanica tested with latest aspectj version 1.8.7. If you updated aspectj version and noticed any issues then please don't hestitate to create new issue or contribute.
- RTW works, you can use regular hystrix-javanica-X.Y.Z
- LTM hasn't been tested but it should work fine.
# How to use
## Hystrix command
### Synchronous Execution
To run method as Hystrix command synchronously you need to annotate method with `@HystrixCommand` annotation, for example
```java
public class UserService {
...
@HystrixCommand
public User getUserById(String id) {
return userResource.getUserById(id);
}
}
...
```
In example above the `getUserById` method will be processed [synchronously](https://github.com/Netflix/Hystrix/wiki/How-To-Use#wiki-Synchronous-Execution) within new Hystrix command.
By default the name of **command key** is command method name: `getUserById`, default **group key** name is class name of annotated method: `UserService`. You can change it using necessary `@HystrixCommand` properties:
```java
@HystrixCommand(groupKey="UserGroup", commandKey = "GetUserByIdCommand")
public User getUserById(String id) {
return userResource.getUserById(id);
}
```
To set threadPoolKey use ```@HystrixCommand#threadPoolKey()```
### Asynchronous Execution
To process Hystrix command asynchronously you should return an instance of `AsyncResult` in your command method as in the example below:
```java
@HystrixCommand
public Future<User> getUserByIdAsync(final String id) {
return new AsyncResult<User>() {
@Override
public User invoke() {
return userResource.getUserById(id);
}
};
}
```
The return type of command method should be Future that indicates that a command should be executed [asynchronously] (https://github.com/Netflix/Hystrix/wiki/How-To-Use#wiki-Asynchronous-Execution).
## Reactive Execution
To perform "Reactive Execution" you should return an instance of `Observable` in your command method as in the example below:
```java
@HystrixCommand
public Observable<User> getUserById(final String id) {
return Observable.create(new Observable.OnSubscribe<User>() {
@Override
public void call(Subscriber<? super User> observer) {
try {
if (!observer.isUnsubscribed()) {
observer.onNext(new User(id, name + id));
observer.onCompleted();
}
} catch (Exception e) {
observer.onError(e);
}
}
});
}
```
In addition to `Observable` Javanica supports the following RX types: `Single` and `Completable`.
Hystrix core supports only one RX type which is `Observable`, `HystrixObservableCommand` requires to return `Observable` therefore javanica transforms `Single` or `Completable` to `Observable` using `toObservable()` method for appropriate type and before returning the result to caller it translates `Observable` to either `Single` or `Completable` using `toSingle()` or `toCompletable()` correspondingly.
HystrixObservable interface provides two methods: ```observe()``` - eagerly starts execution of the command the same as ``` HystrixCommand#queue()``` and ```HystrixCommand#execute()```; ```toObservable()``` - lazily starts execution of the command only once the Observable is subscribed to. To control this behaviour and swith between two modes ```@HystrixCommand``` provides specific parameter called ```observableExecutionMode```.
```@HystrixCommand(observableExecutionMode = EAGER)``` indicates that ```observe()``` method should be used to execute observable command
```@HystrixCommand(observableExecutionMode = LAZY)``` indicates that ```toObservable()``` should be used to execute observable command
**NOTE: EAGER mode is used by default**
## Fallback
Graceful degradation can be achieved by declaring name of fallback method in `@HystrixCommand` like below:
```java
@HystrixCommand(fallbackMethod = "defaultUser")
public User getUserById(String id) {
return userResource.getUserById(id);
}
private User defaultUser(String id) {
return new User("def", "def");
}
```
**_Its important to remember that Hystrix command and fallback should be placed in the same class and have same method signature (optional parameter for failed execution exception)_**.
Fallback method can have any access modifier. Method `defaultUser` will be used to process fallback logic in a case of any errors. If you need to run fallback method `defaultUser` as separate H
没有合适的资源?快使用搜索试试~ 我知道了~
Hystrix.zip
共472个文件
java:411个
gradle:17个
md:16个
需积分: 5 0 下载量 122 浏览量
2023-08-18
09:23:41
上传
评论
收藏 1.01MB ZIP 举报
温馨提示
Hystrix
资源推荐
资源详情
资源评论
收起资源包目录
Hystrix.zip (472个子文件)
gradlew.bat 2KB
core.clj 29KB
core_test.clj 17KB
javadocStyleSheet.css 2KB
.gitignore 751B
build.gradle 4KB
build.gradle 2KB
settings.gradle 2KB
build.gradle 1KB
build.gradle 720B
build.gradle 636B
build.gradle 484B
build.gradle 473B
build.gradle 390B
build.gradle 376B
build.gradle 304B
build.gradle 255B
build.gradle 202B
build.gradle 191B
build.gradle 98B
build.gradle 98B
build.gradle 73B
gradlew 5KB
com.netflix.hystrix.strategy.properties.HystrixDynamicProperties 80B
com.netflix.hystrix.strategy.properties.HystrixDynamicPropertiesFail 13B
gradle-wrapper.jar 53KB
doclet-exclude.jar 3KB
HystrixObservableCommandTest.java 269KB
HystrixCommandTest.java 268KB
HystrixRollingPercentileTest.java 124KB
HystrixCollapserTest.java 98KB
AbstractCommand.java 95KB
HystrixObservableCollapserTest.java 80KB
HystrixCommandProperties.java 40KB
CommonHystrixCommandTests.java 39KB
HystrixRollingNumber.java 31KB
HystrixCircuitBreakerTest.java 31KB
HystrixRollingPercentile.java 30KB
HystrixCollapser.java 29KB
HystrixObservableCollapser.java 29KB
HystrixMetricsPoller.java 27KB
HystrixServoMetricsPublisherCommand.java 26KB
HystrixPropertiesManager.java 26KB
HealthCountsStreamTest.java 25KB
HystrixRollingNumberTest.java 25KB
HystrixCodaHaleMetricsPublisherCommand.java 25KB
CumulativeCommandEventCounterStreamTest.java 24KB
RollingCommandEventCounterStreamTest.java 23KB
CumulativeThreadPoolEventCounterStreamTest.java 23KB
HystrixCommand.java 23KB
RollingThreadPoolEventCounterStreamTest.java 23KB
SerialHystrixDashboardData.java 23KB
SerialHystrixRequestEventsTest.java 22KB
HystrixYammerMetricsPublisherCommand.java 22KB
HystrixTest.java 21KB
RollingCommandLatencyDistributionStreamTest.java 21KB
RollingThreadPoolMaxConcurrencyStreamTest.java 20KB
BasicCommandFallbackTest.java 20KB
HystrixPlugins.java 20KB
HystrixCommandMetrics.java 19KB
HystrixPluginsTest.java 19KB
HystrixCommandExecutionHook.java 19KB
FallbackMethod.java 18KB
HystrixCommandPropertiesTest.java 18KB
HystrixCommandAspect.java 18KB
MetaHolder.java 17KB
BasicErrorPropagationTest.java 17KB
HystrixCollapserProperties.java 16KB
HystrixThreadEventStreamTest.java 16KB
RequestBatch.java 15KB
ExecutionResult.java 15KB
BasicCollapserTest.java 15KB
RollingCommandMaxConcurrencyStreamTest.java 14KB
BasicCommandPropertiesTest.java 14KB
HystrixThreadPoolProperties.java 14KB
BasicObservableTest.java 14KB
HystrixDashboardStreamTest.java 14KB
HystrixConfigurationStreamTest.java 14KB
Striped64.java 14KB
BasicGenericFallbackTest.java 14KB
HystrixUtilizationStreamTest.java 14KB
HystrixServoMetricsPublisherCommandTest.java 14KB
HystrixThreadPoolMetrics.java 13KB
HystrixCircuitBreaker.java 13KB
HystrixThreadPoolPropertiesTest.java 13KB
HystrixServoMetricsPublisherCollapser.java 12KB
HystrixRequestLog.java 12KB
HystrixThreadPool.java 12KB
HystrixCommandTestWithCustomConcurrencyStrategy.java 12KB
CommandExecutionPerfTest.java 12KB
CommandStreamTest.java 12KB
HystrixObservableCommand.java 12KB
MethodProvider.java 12KB
HystrixRequestCache.java 12KB
BasicCacheTest.java 12KB
HystrixConfigurationJsonStream.java 11KB
HystrixCommandConfiguration.java 11KB
HystrixCodaHaleMetricsPublisherCollapser.java 11KB
HystrixYammerMetricsPublisherCollapser.java 11KB
HystrixServoMetricsPublisherThreadPool.java 11KB
共 472 条
- 1
- 2
- 3
- 4
- 5
资源评论
hello_中年人
- 粉丝: 7
- 资源: 324
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功