七.Hystrix Timeout機制

由於在一個複雜的系統裏,可能你的依賴接口的性能很不穩定,有時候2ms,200ms,2s,若是你不對各類依賴接口的調用作超時的控制來給你的服務提供安全保護措施,那麼極可能你的服務就被依賴服務的性能給拖死了,大量的接口調用很慢,大量線程就卡死了。安全

(1)execution.isolation.thread.timeoutInMillisecondside

  手動設置timeout時長,一個command運行超出這個時間,就被認爲是timeout,而後將hystrix command標識爲timeout,同時執行fallback降級邏輯,默認是1000,也就是1000毫秒。性能

HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(int value)

 

(2)execution.timeout.enabledui

  控制是否要打開timeout機制,默認是truethis

HystrixCommandProperties.Setter().withExecutionTimeoutEnabled(boolean value)

 

/**
 * 獲取商品信息
 * @author 張三丰
 *
 */
public class GetProductInfoCommand extends HystrixCommand<ProductInfo> {

    private Long productId;
    
    public GetProductInfoCommand(Long productId) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ProductInfoService"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("GetProductInfoCommand"))
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("GetProductInfoPool"))
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                        .withCoreSize(10)
                        .withMaxQueueSize(12)
                        .withQueueSizeRejectionThreshold(15)) 
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withCircuitBreakerRequestVolumeThreshold(30)
                        .withCircuitBreakerErrorThresholdPercentage(40)
                        .withCircuitBreakerSleepWindowInMilliseconds(3000)
                        .withExecutionTimeoutInMilliseconds(500)//超時時間500毫秒
                        .withFallbackIsolationSemaphoreMaxConcurrentRequests(30))  
                );  
        this.productId = productId;
    }
    
    @Override
    protected ProductInfo run() throws Exception {
        System.out.println("調用接口,查詢商品數據,productId=" + productId); 
        
        
        if(productId.equals(-2L)) {
            Thread.sleep(3000);  
        }
        

        return JSONObject.parseObject("數據", ProductInfo.class);  
    }

    
    @Override
    protected ProductInfo getFallback() {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setName("降級商品");  
        return productInfo;
    }
    
}
相關文章
相關標籤/搜索