Hystrix不会中断长时间运行的线程

时间:2016-06-03 07:57:54

标签: thread-safety threadpoolexecutor fallback hystrix

我是hystrix的新手,并在POC下面创建,它从下面的用例中随机选择。

  1. 零错误代码(成功)
  2. 非零错误代码
  3. 运行时异常
  4. 无限循环
  5. 当它选择第4个时,它不会中断线程。如果我将Thread.sleep()放置更长时间,那么它会中断,但不会中断无限循环。

    有人能告诉我在HystrixCommand中执行任务是否有任何错误吗?如何使用hystrix中断长/无限运行的线程?

    public class HystrixTesting extends HystrixCommand<HystrixResult> {
    
        private String institutionId;
        private boolean isTimedOut = true;
        private boolean isRunExecuted = false;
        private HystrixResult hystrixResult = new HystrixResult();
    
        private HystrixErrorMap map = HystrixErrorMap.getInstance();
        String executionType;
    
        private Logger logger = LoggerFactory.getLogger(HystrixTesting.class);
    
        public HystrixTesting(String institutionId, HystrixResult hystrixResult) {
            super(Setter.withGroupKey(
                    HystrixCommandGroupKey.Factory.asKey("HystrixTest"))
                    .andCommandKey(HystrixCommandKey.Factory.asKey(institutionId)));
            this.hystrixResult = hystrixResult;
            this.institutionId = institutionId;
        }
    
        @Override
        protected HystrixResult run() throws WIFrameworkException {
    
            isRunExecuted = true;
            logger.info("Hystrix:: Execution started for InstitutionId="
                    + institutionId);
            HystrixTask hystrixTask = new HystrixTask();
            try {
                hystrixResult = hystrixTask.executeTask(institutionId);
            } catch (Exception e) {
                isTimedOut = false;
            }
            logger.info("Hystrix:: Execution finished for InstitutionId="
                    + institutionId);
    
            int errorCode = hystrixResult.getScriptExecutionStatusCode();
            String errorMessage = hystrixResult.getScriptExecutionStatusMessage();
            if (HystrixErrorMap.isInErrorCodeList(errorCode)) {
                map.add(institutionId, new ContextInfo(errorCode, errorMessage));
                isTimedOut = false;
                logger.info("Hystrix:: Throwing runtime exception in hystrix command due to ErrorCode="
                        + errorCode + ", InstitutionId=" + institutionId);
                throw new RuntimeException();
            }
    
            if (map.get(institutionId) != null)
                map.remove(institutionId);
            isTimedOut = false;
            return hystrixResult;
        }
    
        @Override
        protected HystrixResult getFallback() {
            logger.info("Hystrix:: Fallback method called, threw an Exception in run() or hystrix has already blocked the execution for InstitutionId="
                    + institutionId);
    
            if (isTimedOut && isRunExecuted) {
                String errMsg = "Hystrix:: Hystrix Command Timeout Occured while executing request for InstitutionId="
                        + institutionId;
                logger.error(errMsg + ", InstitutionId=" + institutionId);
    
                hystrixResult.setScriptExecutionStatus(102, errMsg);
                map.add(institutionId, new ContextInfo(102, errMsg));
            } else if (!isRunExecuted) {
                ContextInfo staleContext = map.get(institutionId);
    
                logger.error("Hystrix:: Hystrix blocked the execution for InstitutionId="
                        + institutionId
                        + " due to ErrorCode="
                        + staleContext.getErrorCode()
                        + ", ErrorMessage="
                        + staleContext.getErrorMessage());
    
                hystrixResult.setScriptExecutionStatus(staleContext.getErrorCode(),
                        "Circuit is broken for " + institutionId + " due to "
                                + staleContext.getErrorMessage());
            }
            return hystrixResult;
        }
    
    }
    
    **HystrixTask.java**
    
    public class HystrixTask {
    
        private Logger logger = LoggerFactory.getLogger(HystrixTask.class);
    
        static List<Integer> list = new ArrayList<Integer>();
    
        public static int zeroErrorCounter = 1;
        public static int nonZeroErrorCounter = 1;
        public static int runTimeErrorCounter = 1;
        public static int timeOutErrorCounter = 1;
    
        static {
            list.add(1);
            list.add(2);
            list.add(3);
            list.add(4);
        }
    
        /**
         * Provides the output randomly 1. Successful(0 Error code) 2. Non zero
         * error code 3. Runtime Exception 4. Timeout
         * 
         * @param institutionId
         * @param scriptctx
         * @param executionType
         * @return
         * @throws InterruptedException
         */
        public HystrixResult executeTask(String institutionId) {
            logger.info("inside executeTask() Hystrix.getCurrentThreadExecutingCommand().name():"
                    + Hystrix.getCurrentThreadExecutingCommand().name());
    
            HystrixResult result = new HystrixResult();
            try {
                int random = list.get(new Random().nextInt(list.size()));
                switch (random) {
                case 1:
                    result.setScriptExecutionStatus(0, "Successfully executed");
                    logger.info("Hystrix:: Zero Error request served:"
                            + zeroErrorCounter++);
                    return result;
                case 2:
                    result.setScriptExecutionStatus(101, "Layout changed");
                    logger.info("Hystrix:: Non Zero Error request served:"
                            + nonZeroErrorCounter++);
                    return result;
                case 3:
                    logger.info("Hystrix:: Run time Error request served:"
                            + runTimeErrorCounter++);
                    int error = 10 / 0;
                case 4:
                    result.setScriptExecutionStatus(1000, "Timeout exception");
                    logger.info("Hystrix:: Timeout Error request started for:"
                            + timeOutErrorCounter++);
                    try {
                        Thread.sleep(101000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    logger.info("Hystrix:: Timeout Error request served:"
                            + timeOutErrorCounter);
                    return result;
                default:
                    logger.info("Hystrix:: default:");
                    return null;
                }
            } catch (Exception e) {
                logger.info("inside exception Hystrix.getCurrentThreadExecutingCommand().name():"
                        + Hystrix.getCurrentThreadExecutingCommand().name());
                result.setScriptExecutionStatus(1001, "Run time exception");
                logger.info("Hystrix:: Cautht: " + runTimeErrorCounter);
                return result;
            }
        }
    }
    

0 个答案:

没有答案