码迷,mamicode.com
首页 > 其他好文 > 详细

hystrix源码小贴士之调用timeout实现

时间:2017-12-18 18:57:45      阅读:359      评论:0      收藏:0      [点我收藏+]

标签:exe   execution   top   ati   set   nts   script   runnable   cut   

  AbstractCommand执行命令前首先会判断是否开启了timeout。

if (properties.executionTimeoutEnabled().get()) {
            execution = executeCommandWithSpecifiedIsolation(_cmd)
                    .lift(new HystrixObservableTimeoutOperator<R>(_cmd));
        } else {
            execution = executeCommandWithSpecifiedIsolation(_cmd);
        }

  HystrixObservableTimeoutOperator的核心是内部又一个定时器,当达到timeout时间时,将命令状态设置成timeout,向eventNotifier发送timeout事件,取消监听,返回一个HystrixTimeoutException的onError。

private static class HystrixObservableTimeoutOperator<R> implements Operator<R, R> {
       ....
        @Override
        public Subscriber<? super R> call(final Subscriber<? super R> child) {
            final CompositeSubscription s = new CompositeSubscription();
            child.add(s);

            /*
             * Define the action to perform on timeout outside of the TimerListener to it can capture the HystrixRequestContext
             * of the calling thread which doesn‘t exist on the Timer thread.
             */
            final HystrixContextRunnable timeoutRunnable = new HystrixContextRunnable(originalCommand.concurrencyStrategy, new Runnable() {

                @Override
                public void run() {
                    child.onError(new HystrixTimeoutException());
                }
            });

            TimerListener listener = new TimerListener() {
                @Override
                public void tick() {
                    // if we can go from NOT_EXECUTED to TIMED_OUT then we do the timeout codepath
                    // otherwise it means we lost a race and the run() execution completed or did not start
                    if (originalCommand.isCommandTimedOut.compareAndSet(TimedOutStatus.NOT_EXECUTED, TimedOutStatus.TIMED_OUT)) {
                        // report timeout failure
                        originalCommand.eventNotifier.markEvent(HystrixEventType.TIMEOUT, originalCommand.commandKey);
                        // shut down the original request
                        s.unsubscribe();
                        timeoutRunnable.run();
                        //if it did not start, then we need to mark a command start for concurrency metrics, and then issue the timeout
                    }
                }
                @Override
                public int getIntervalTimeInMilliseconds() {
                    return originalCommand.properties.executionTimeoutInMilliseconds().get();
                }
            };
      ...
} }

 

hystrix源码小贴士之调用timeout实现

标签:exe   execution   top   ati   set   nts   script   runnable   cut   

原文地址:http://www.cnblogs.com/zhangwanhua/p/8041119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!