package cc.smtweb.framework.core.systask;

import cc.smtweb.framework.core.cache.redis.RedisManager;
import cc.smtweb.framework.core.exception.SwException;
import cc.smtweb.framework.core.util.DateUtil;
import cc.smtweb.framework.core.util.StringUtil;

//redis控制的互斥执行，一般用于定时任务，避免多服务器重复执行
public class SingleRequestHelper {

    public static interface ISingleWork {
        void doSingleWork();

    }

    public static void singleRequest(String region_key, String key, ISingleWork singleWork) {
        singleRequest(region_key, key, "其他人正在执行该操作，请等待！", singleWork);
    }

    public static void singleRequest(String region_key, String key, String tip_msg, ISingleWork singleWork) {
        boolean clearCache = false;
        try {
            String lastTime = RedisManager.getInstance().hGet(region_key, key, String.class);
            if (StringUtil.isNotEmpty(lastTime)) {
                throw new SwException(tip_msg);
            }
            RedisManager.getInstance().hSet(region_key, key, DateUtil.nowDateString());
            clearCache = true;
            singleWork.doSingleWork();
        } finally {
            if (clearCache) RedisManager.getInstance().hdel(region_key, key);
        }
    }
}
