RedisLock.java 1.64 KB
package com.yohoufo.common.cache;

import com.yoho.core.redis.cluster.annotation.Redis;
import com.yoho.core.redis.cluster.operations.nosync.YHRedisTemplate;
import com.yoho.core.redis.cluster.operations.nosync.YHValueOperations;
import com.yoho.core.redis.cluster.operations.serializer.RedisKeyBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisLock {

    @Redis("gwNoSyncRedis")
    private YHRedisTemplate redis;

    @Redis("gwNoSyncRedis")
    private YHValueOperations valueOperations;

    public boolean acquire(RedisKeyBuilder key, String value, final long timeout, final TimeUnit unit) {
        try {
            String redisLockValue = valueOperations.get(key);
            if (StringUtils.isNoneBlank(redisLockValue)) {
                return false;
            }
            valueOperations.set(key, value, timeout, unit);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public void release(RedisKeyBuilder key, String value) {
        try {
            deleteKeyIfValueEquals(key, value);
        } catch (Exception e) {
            try {
                deleteKeyIfValueEquals(key, value);
            } catch (Exception e1) {
                log.warn("release lock {} fail", key, e);
            }
        }
    }

    private void deleteKeyIfValueEquals(RedisKeyBuilder key, String value) {
        String redisLockValue = valueOperations.get(key);
        if (value.equals(redisLockValue)) {
            redis.delete(key);
        }
    }


}