All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dennisit.vplus.data.criteria.action.RetryAction Maven / Gradle / Ivy

/*--------------------------------------------------------------------------
 *  Copyright (c) 2010-2020, Elon.su All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the elon developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: Elon.su, you can also mail [email protected]
 *--------------------------------------------------------------------------
*/
package com.github.dennisit.vplus.data.criteria.action;

import com.github.dennisit.vplus.data.criteria.RetryCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 重试行为定义
 * @author Elon.su
 */
public final class RetryAction {

    private static final Logger LOG = LoggerFactory.getLogger(RetryAction.class);

    public static final Integer DEFAULT_RETRY_TIMES = 3;

    private RetryAction(){

    }

    /**
     * 重试行为处理, 使用默认重试次数3次
     * @param func 重试行为约束
     * @param  最终处理结果
     * @return 最终处理结果
     */
    public static  R doWithTry(RetryCriteria func){
        return doWithTry(func, DEFAULT_RETRY_TIMES);
    }


    /**
     * 带重试的处理。
     * @param func  处理函数
     * @param tryTimes 重试次数
     * @param  最终处理结果
     * @return 最终处理结果
     */
    public static  R doWithTry(RetryCriteria func, int tryTimes) {
        for (int nowTimes = 0; nowTimes < tryTimes; nowTimes++) {
            R r = func.handle();
            if (null != r) {
                return r;
            }
        }
        return null;
    }


    public static void main(String[] args) {
        String result = RetryAction.doWithTry(new RetryCriteria() {
            @Override
            public String handle() {
                try {
                    throw new RuntimeException("重试示例");
                    //return "success";
                } catch (Exception e) {
                    LOG.error("RetryUtils.doWithTry(...) error,", e);
                }
                return null;
            }
        }, 3);
        System.out.println(result);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy