netflix hystrix 使用詳解
阿新 • • 發佈:2019-02-09
1. 依賴引入
pom.xml
<properties> <hystrix-version> 1.4 . 22 </hystrix-version> </properties> <dependencies> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>${hystrix-version}</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-metrics-event-stream</artifactId> <version>${hystrix-version}</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-javanica</artifactId> <version>${hystrix-version}</version> </dependency> <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-servo-metrics-publisher</artifactId> <version>${hystrix-version}</version> </dependency> </dependencies> |
applicationContext.xml:
<aop:aspectj-autoproxy/> <bean id= "hystrixAspect" class = "com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect" /> |
web.xml:
<servlet> <display-name>HystrixMetricsStreamServlet</display-name> <servlet-name>HystrixMetricsStreamServlet</servlet-name> <servlet- class >com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet</servlet- class > </servlet> <servlet-mapping> <servlet-name>HystrixMetricsStreamServlet</servlet-name> <url-pattern>/hystrix.stream</url-pattern> </servlet-mapping> |
jmonitor:
collector=jvm,appdata,http |
2. 使用
2.1 Hystrix command
2.1.1 同步執行
public class UserService { ... @HystrixCommand (groupKey= "UserGroup" , commandKey = "GetUserByIdCommand" ) public User getUserById(String id) { return userResource.getUserById(id); } } |
2.1.2 非同步執行
@HystrixCommand public Future<User> getUserByIdAsync( final String id) { return new AsyncResult<User>() { @Override public User invoke() { return userResource.getUserById(id); } }; } |
2.1.3 反應執行
@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); } } }); } |
2.1.4 三種模式使用區別
- 同步執行:當執行到註解方法時,程式會順序執行。
- 非同步執行:當執行到註解方法時,會併發非同步執行,返回一個Future物件,後面使用.get()方法來阻塞拿到結果。如果有多個方法時,執行時間就是其中最長的一個服務的執行時間。
- 反應執行:當執行到註解方法時,返回一個觀察者。支援EAGER和LAZY模式。和同步非同步執行的區別是,當對多個方法之間的返回結果不需要做合併而是希望當多個方法返回時觸發一些事件時比較適合使用該模式。
2.2 Fallback
@HystrixCommand (fallbackMethod = "fallback1" ) User getUserById(String id) { throw new RuntimeException( "getUserById command failed" ); }
|