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 同步執行

public  class  UserService {
...
     @HystrixCommand
     public  User getUserById(String id) {
         return  userResource.getUserById(id);
     }
}

2.1.2 異步執行

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 反應執行()

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 三種模式使用區別

  • 同步執行:當執行到注解方法時,程序會順序執行。
  • 異步執行:當執行到注解方法時,會並發異步執行,返回一個Future對象,后面使用.get()方法來阻塞拿到結果。如果有多個方法時,執行時間就是其中最長的一個服務的執行時間。
  • 反應執行:當執行到注解方法時,返回一個觀察者。支持EAGER和LAZY模式。和同步異步執行的區別是,當對多個方法之間的返回結果不需要做合並而是希望當多個方法返回時觸發一些事件時比較適合使用該模式。

反應執行沒太明白,如果需要了解可以先參考下這個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應該和注解方法在同一類下
  • fallback的返回值和參數列表應該和注解方法一致,如果需要異常,則在末尾添加Throwable參數,對訪問修飾符無要求
  • fallback方法上可以繼續添加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

  默認值:當前執行方法名

execution.isolation.strategy

隔離策略,有THREAD和SEMAPHORE

默認使用THREAD模式,以下幾種可以使用SEMAPHORE模式:

  • 只想控制並發度
  • 外部的方法已經做了線程隔離
  • 調用的是本地方法或者可靠度非常高、耗時特別小的方法(如medis)

execution.isolation.thread.timeoutInMilliseconds

 

超時時間

默認值:1000

在THREAD模式下,達到超時時間,可以中斷

在SEMAPHORE模式下,會等待執行完成后,再去判斷是否超時

設置標准:

有retry,99meantime+avg meantime

沒有retry,99.5meantime

execution.timeout.enabled

是否打開超時  

execution.isolation.thread.interruptOnTimeout

是否打開超時線程中斷 THREAD模式有效

execution.isolation.semaphore.maxConcurrentRequests

信號量最大並發度 SEMAPHORE模式有效,默認值:10

fallback.isolation.semaphore.maxConcurrentRequests

fallback最大並發度 默認值:10

circuitBreaker.requestVolumeThreshold

熔斷觸發的最小個數/10s 默認值:20

circuitBreaker.sleepWindowInMilliseconds

熔斷多少秒后去嘗試請求 默認值:5000

circuitBreaker.errorThresholdPercentage

失敗率達到多少百分比后熔斷

默認值:50

主要根據依賴重要性進行調整

circuitBreaker.forceClosed

是否強制關閉熔斷 如果是強依賴,應該設置為true

coreSize

線程池coreSize

默認值:10

設置標准:qps*99meantime+breathing room

maxQueueSize

請求等待隊列

默認值:-1

如果使用正數,隊列將從SynchronizeQueue改為LinkedBlockingQueue



轉自:http://blog.csdn.net/zheng0518/article/details/51713900


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM