码迷,mamicode.com
首页 > 其他好文 > 详细

一个Redis实现的分布式锁

时间:2016-10-18 18:32:50      阅读:3595      评论:0      收藏:0      [点我收藏+]

标签:

 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisLock.class);

    @Autowired
    protected RedisTemplate<String, String> redisTemplate;

    private static final long DEFAULT_WAIT_LOCK_TIME_OUT = 60000;//60s 有慢sql,超时时间设置长一点
    private static final long DEFAULT_EXPIRE = 80;//80s 有慢sql,超时时间设置长一点

    /**
     * 等待锁的时间,单位为ms
     *
     * @param key
     * @param timeout ms
     */
    public void lock(String key, long timeout) {
        String lockKey = generateLockKey(key);
        long start = System.currentTimeMillis();
        try {
            while ((System.currentTimeMillis() - start) < timeout) {
                if (redisTemplate.getConnectionFactory().getConnection().setNX(lockKey.getBytes(), new byte[0])) {
                    redisTemplate.expire(lockKey, DEFAULT_EXPIRE, TimeUnit.SECONDS);//暂设置为80s过期,防止异常中断锁未释放
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("add RedisLock[" + key + "].");
                    }
                    break;
                }
                TimeUnit.SECONDS.sleep(3);
            }
        } catch (Exception e) {
            unlock(lockKey);
        }
    }

    public void unlock(String key) {
        String lockKey = generateLockKey(key);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("release RedisLock[" + lockKey + "].");
        }
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.del(lockKey.getBytes());
        connection.close();
    }

    private String generateLockKey(String key) {
        return String.format("LOCK:%s", key);
    }

    public void lock(String key) {
        lock(key, DEFAULT_WAIT_LOCK_TIME_OUT);
    }

}

 

一个Redis实现的分布式锁

标签:

原文地址:http://www.cnblogs.com/softidea/p/5974095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!