Hystrix Timeout机制

本文探讨了在复杂系统中如何使用Hystrix的execution.isolation.thread.timeoutInMilliseconds和execution.timeout.enabled来实现服务调用的超时控制,防止性能不稳定的服务影响整个系统。通过实例讲解了GetProductInfoCommand中的超时设置和fallback逻辑。
摘要由CSDN通过智能技术生成

因为在一个复杂的系统里,可能你的依赖接口的性能很不稳定,有时候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;
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值