Hystrix使用Commond的三种方式
目錄(?)[-]
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. 使用
這里只講注解的使用方式以及比較重要的部分,如果需要了解全部查看:https://github.com/Netflix/Hystrix/wiki/How-To-Use
2.1?Hystrix command
2.1.1 同步執(zhí)行
| public?class?UserService { ... ????@HystrixCommand ????public?User getUserById(String id) { ????????return?userResource.getUserById(id); ????} } |
2.1.2 異步執(zhí)行
| public?class?UserService { ... ? ? @HystrixCommand ????public?Future<User> getUserByIdAsync(final?String id) { ????????return?new?AsyncResult<User>() { ????????????@Override ????????????public?User invoke() { ????????????????return?userResource.getUserById(id); ????????????} ????????}; ????} } |
2.1.3 反應(yīng)執(zhí)行()
| public?class?UserService { ? ? ... ? ? @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(userResource.getUserById(id)); ????????????????????????????observer.onCompleted(); ????????????????????????} ????????????????????}?catch?(Exception e) { ????????????????????????observer.onError(e); ????????????????????} ????????????????} ????????????}); ????} } |
2.1.4 三種模式使用區(qū)別
- 同步執(zhí)行:當執(zhí)行到注解方法時,程序會順序執(zhí)行。
- 異步執(zhí)行:當執(zhí)行到注解方法時,會并發(fā)異步執(zhí)行,返回一個Future對象,后面使用.get()方法來阻塞拿到結(jié)果。如果有多個方法時,執(zhí)行時間就是其中最長的一個服務(wù)的執(zhí)行時間。
- 反應(yīng)執(zhí)行:當執(zhí)行到注解方法時,返回一個觀察者。支持EAGER和LAZY模式。和同步異步執(zhí)行的區(qū)別是,當對多個方法之間的返回結(jié)果不需要做合并而是希望當多個方法返回時觸發(fā)一些事件時比較適合使用該模式。
反應(yīng)執(zhí)行沒太明白,如果需要了解可以先參考下這個https://mcxiaoke.gitbooks.io/rxdocs/content/Intro.html
2.2?Fallback
| @HystrixCommand(fallbackMethod =?"fallback1") User getUserById(String id) { ????throw?new?RuntimeException("getUserById command failed"); } @HystrixCommand(fallbackMethod =?"fallback2") User fallback1(String id, Throwable e) { ????assert?"getUserById command failed".equals(e.getMessage()); ????throw?new?RuntimeException("fallback1 failed"); } @HystrixCommand(fallbackMethod =?"fallback3") User fallback2(String id) { ????throw?new?RuntimeException("fallback2 failed"); } |
注意點:
- fallback應(yīng)該和注解方法在同一類下
- fallback的返回值和參數(shù)列表應(yīng)該和注解方法一致,如果需要異常,則在末尾添加Throwable參數(shù),對訪問修飾符無要求
- fallback方法上可以繼續(xù)添加fallback
command和fallback只支持以下幾種組合:
- sync command, sync fallback
- async command, sync fallback
- async command, async fallback
2.3 Error Propagation
| @HystrixCommand(ignoreExceptions = {BadRequestException.class}) ????public?User getUserById(String id) { ????????return?userResource.getUserById(id); ????} |
當遇到BadRequestException時不會進入fallback,而是直接拋出異常
2.4?Configuration
| @HystrixCommand(groupKey="UserGroup", commandKey =?"GetUserByIdCommand", ????????????????commandProperties = { ????????????????????????@HystrixProperty(name =?"execution.isolation.thread.timeoutInMilliseconds", value =?"500") ????????????????}, ????????????????threadPoolProperties = { ????????????????????????@HystrixProperty(name =?"coreSize", value =?"30"), ????????????????????????@HystrixProperty(name =?"maxQueueSize", value =?"101"), ????????????????????????@HystrixProperty(name =?"keepAliveTimeMinutes", value =?"2"), ????????????????????????@HystrixProperty(name =?"queueSizeRejectionThreshold", value =?"15"), ????????????????????????@HystrixProperty(name =?"metrics.rollingStats.numBuckets", value =?"12"), ????????????????????????@HystrixProperty(name =?"metrics.rollingStats.timeInMilliseconds", value =?"1440") ????????}) |
| groupKey | 表示所屬的group,一個group共用線程池 | 默認值:getClass().getSimpleName(); |
| commandKey | ? | 默認值:當前執(zhí)行方法名 |
| execution.isolation.strategy | 隔離策略,有THREAD和SEMAPHORE | 默認使用THREAD模式,以下幾種可以使用SEMAPHORE模式:
|
| execution.isolation.thread.timeoutInMilliseconds ? | 超時時間 | 默認值:1000 在THREAD模式下,達到超時時間,可以中斷 在SEMAPHORE模式下,會等待執(zhí)行完成后,再去判斷是否超時 設(shè)置標準: 有retry,99meantime+avg meantime 沒有retry,99.5meantime |
| execution.timeout.enabled | 是否打開超時 | ? |
| execution.isolation.thread.interruptOnTimeout | 是否打開超時線程中斷 | THREAD模式有效 |
| execution.isolation.semaphore.maxConcurrentRequests | 信號量最大并發(fā)度 | SEMAPHORE模式有效,默認值:10 |
| fallback.isolation.semaphore.maxConcurrentRequests | fallback最大并發(fā)度 | 默認值:10 |
| circuitBreaker.requestVolumeThreshold | 熔斷觸發(fā)的最小個數(shù)/10s | 默認值:20 |
| circuitBreaker.sleepWindowInMilliseconds | 熔斷多少秒后去嘗試請求 | 默認值:5000 |
| circuitBreaker.errorThresholdPercentage | 失敗率達到多少百分比后熔斷 | 默認值:50 主要根據(jù)依賴重要性進行調(diào)整 |
| circuitBreaker.forceClosed | 是否強制關(guān)閉熔斷 | 如果是強依賴,應(yīng)該設(shè)置為true |
| coreSize | 線程池coreSize | 默認值:10 設(shè)置標準:qps*99meantime+breathing room |
| maxQueueSize | 請求等待隊列 | 默認值:-1 如果使用正數(shù),隊列將從SynchronizeQueue改為LinkedBlockingQueue |
轉(zhuǎn)自:http://blog.csdn.net/zheng0518/article/details/51713900
總結(jié)
以上是生活随笔為你收集整理的Hystrix使用Commond的三种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UI开发模式-容器模式
- 下一篇: 为Feign设置Header信息