Search in sources :

Example 1 with TimeOutException

use of info.xiancloud.core.support.cache.exception.TimeOutException in project xian by happyyangyuan.

the class DistributedLock method lock.

/**
 * @param cacheConfigBean    cacheConfigBean
 * @param key                key
 * @param value              vlaue
 * @param expireTimeInSecond 单位: 秒, KEY 过期时间
 * @param timeOutInSecond    单位: 秒, 获取锁超时时间
 * @return DistributedLock
 * @throws TimeOutException
 */
public static DistributedLock lock(CacheConfigBean cacheConfigBean, String key, Object value, int expireTimeInSecond, int timeOutInSecond) throws TimeOutException, RuntimeException {
    final long applyTime = System.currentTimeMillis();
    final int _expireTimeInSecond = expireTimeInSecond < 1 ? 3 : expireTimeInSecond;
    final int _timeOutInSecond = timeOutInSecond < 1 ? 3 : timeOutInSecond;
    if (expireTimeInSecond != _expireTimeInSecond)
        LOG.warn(String.format("key: %s, 原 expireTime: %s < 1, 校正为现 expireTime: %s", key, expireTimeInSecond, _expireTimeInSecond));
    if (timeOutInSecond != _timeOutInSecond)
        LOG.warn(String.format("key: %s, 原 timeOutInSecond: %s < 1, 校正为现 timeOutInSecond: %s", key, timeOutInSecond, _timeOutInSecond));
    final String lockKey = "LOCK_" + key;
    UnitResponse unitResponseObject = SyncXian.call("cache", "distributedLock", new JSONObject() {

        {
            put("cacheConfig", cacheConfigBean);
            put("key", lockKey);
            put("value", value);
            put("expireTimeInSecond", _expireTimeInSecond);
            put("timeOutInSecond", _timeOutInSecond);
        }
    });
    final long receiveTime = System.currentTimeMillis();
    if (unitResponseObject.succeeded()) {
        int autoIncrement = AUTO_INCREMENT.incrementAndGet();
        if (!EnvUtil.getEnv().equals(EnvUtil.PRODUCTION))
            LOG.info(String.format("锁编号: %s, key: %s, lockKey: %s, value: %s, 分布式加锁, 成功, 耗时: %s 毫秒", autoIncrement, key, lockKey, value, (receiveTime - applyTime)));
        return new DistributedLock(autoIncrement, key, lockKey, value);
    } else if (unitResponseObject.getCode().equals(Group.CODE_TIME_OUT))
        throw new TimeOutException(String.format("分布式加锁, 超时, key: %s, lockKey: %s, 耗时: %s 毫秒", key, lockKey, (receiveTime - applyTime)));
    else
        throw new RuntimeException(String.format("分布式加锁, 异常, key: %s, lockKey: %s, 耗时: %s 毫秒", key, lockKey, (receiveTime - applyTime)));
}
Also used : TimeOutException(info.xiancloud.core.support.cache.exception.TimeOutException) JSONObject(com.alibaba.fastjson.JSONObject) UnitResponse(info.xiancloud.core.message.UnitResponse)

Aggregations

JSONObject (com.alibaba.fastjson.JSONObject)1 UnitResponse (info.xiancloud.core.message.UnitResponse)1 TimeOutException (info.xiancloud.core.support.cache.exception.TimeOutException)1