七.Hystrix Timeout機制


因為在一個復雜的系統里,可能你的依賴接口的性能很不穩定,有時候2ms,200ms,2s,如果你不對各種依賴接口的調用做超時的控制來給你的服務提供安全保護措施,那么很可能你的服務就被依賴服務的性能給拖死了,大量的接口調用很慢,大量線程就卡死了。

(1)execution.isolation.thread.timeoutInMilliseconds

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

HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(int value)

 

(2)execution.timeout.enabled

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

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;
    }
    
}

 


免責聲明!

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



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