Redis分布式锁

来源:互联网 发布:昊海软件 编辑:程序博客网 时间:2024/06/05 04:12

       最近在学习Redis 过程中,了解到redis的可以作为分布式锁的使用,这里学习记录下。

一、背景介绍:

       在很多互联网产品应用中,有些场景需要加锁处理,比如:秒杀,全局递增ID,楼层生成等等。大部分的解决方案是基于DB实现的,Redis为单进程单线程模式,采用队列模式将并发访问变成串行访问,且多客户端对redis的连接并不存在竞争关系。其次Redis提供一些命令SETNX,GETSET,可以方便实现分布式锁机制。


二、使用分布式锁需要满足的几个条件

1.系统是一个分布式系统(关键是分布式,单机的可以使用ReentrantLock或者synchonized代码快来实现)

2.共享资源(各个系统访问同一资源,资源的载体可能是传统关系数据库或者NoSQL)

3.同步访问(即有很多歌进程同时访问一个共享资源。没有同步访问,就不会存在竞争关系)


三、实现方式

1、使用setnx命令实现

    redis提供了丰富的可操作命令,首先我们来看下下面几个命令

    (1) setnx 命令 (SET IF NOT EXISTS):

    语法:
    SETNX key value
    功能:
    当且仅当 key 不存在,将 key 的值设为 value ,并返回1;若给定的 key 已经存在,则 SETNX 不做任何动作,并返回0。

    (2) GET命令

    语法:

    GET key

    功能:
    返回 key 所关联的字符串值,如果 key 不存在那么返回特殊值 nil 。

    (3) DEL命令

    DEL key (KEY ..)

    功能:
     删除给定的一个或多个 key ,不存在的 key 会被忽略。

加锁实现

SETNX 可以直接加锁操作,比如说对某个关键词foo加锁,客户端可以尝试
SETNX foo.lock <current unix time>

如果返回1,表示客户端已经获取锁,可以往下操作,操作完成后,通过
DEL foo.lock

命令来释放锁。
如果返回0,说明foo已经被其他客户端上锁,如果锁是非堵塞的,可以选择返回调用。如果是堵塞调用调用,就需要进入以下个重试循环,直至成功获得锁或者重试超时。理想是美好的,现实是残酷的。仅仅使用SETNX加锁带有竞争条件的,在某些特定的情况会造成死锁错误。


 2、使用inrr 命令

INCR key

将 key 中储存的数字值增一。

如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。

如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。



四、解决死锁

在上面的处理方式中,如果获取锁的客户端端执行时间过长,进程被kill掉,或者因为其他异常崩溃,导致无法释放锁,就会造成死锁。所以,需要对加锁要做时效性检测。因此,我们在加锁时,把当前时间戳作为value存入此锁中,通过当前时间戳和Redis中的时间戳进行对比,如果超过一定差值,认为锁已经时效,防止锁无限期的锁下去,但是,在大并发情况,如果同时检测锁失效,并简单粗暴的删除死锁,再通过SETNX上锁,可能会导致竞争条件的产生,即多个客户端同时获取锁。

C1获取锁,并崩溃。C2和C3调用SETNX上锁返回0后,获得foo.lock的时间戳,通过比对时间戳,发现锁超时。
C2 向foo.lock发送DEL命令。
C2 向foo.lock发送SETNX获取锁。
C3 向foo.lock发送DEL命令,此时C3发送DEL时,其实DEL掉的是C2的锁。
C3 向foo.lock发送SETNX获取锁。

此时C2和C3都获取了锁,产生竞争条件,如果在更高并发的情况,可能会有更多客户端获取锁。所以,DEL锁的操作,不能直接使用在锁超时的情况下,幸好我们有GETSET方法,假设我们现在有另外一个客户端C4,看看如何使用GETSET方式,避免这种情况产生。

C1获取锁,并崩溃。C2和C3调用SETNX上锁返回0后,调用GET命令获得foo.lock的时间戳T1,通过比对时间戳,发现锁超时。
C4 向foo.lock发送GESET命令,
GETSET foo.lock <current unix time>
并得到foo.lock中老的时间戳T2


五、代码实现

(1) 使用setnx命令实现

public class setnxLockDemo {    private StopWatch stopWatch = new StopWatch();    private int tryLockCount = 0;    private String key;    private int maxLockSeconds;    private static final String KEY = "inrr.test";    private static final String ip = "xxxxxx";    private static final int port = 6379;    private static final int timeOut = 2000;    /**     * 适用于:     * 任务处理时长在 百毫秒级 <p>     * 重试获取锁的间隔在 十毫秒级 <p>     *     * @param key     * @param maxLockSeconds 防止客户端挂掉,无法自己手动释放锁的时候,锁自动失效时间。     *                    这个值应该设置的大些,让它在客户端正常运行的时都手动释放,而不是远程自动释放。     */    public setnxLockDemo(String key, int maxLockSeconds) {        this.key = key;        this.maxLockSeconds = maxLockSeconds;    }    public void lock() {        if (stopWatch.isStarted()) {            throw new IllegalStateException("未拿到锁,该方法已被调用");        }        while (true) {            if (setnx(key) == 1L) {                stopWatch.start(); // 本地时间要比远程时间先计                expire(key, maxLockSeconds);                return;            } else {                try {                    Thread.sleep(RandomUtils.nextInt(15, 50));                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }    /**     * 如果本地计时器发现一秒内远程会自动释放锁,这个方法就不执行任何操作了     */    public void unlock() {        if (stopWatch.getTime() / 1000L < maxLockSeconds) {            CodisConnector.del(key);        }    }    public static long setnx(String key) {        //此处假设已经拿到配置        JedisPoolConfig config = new JedisPoolConfig();        JedisPool pool = new JedisPool(config, ip, port, timeOut);        Jedis jedis = pool.getResource();        try {            return jedis.setnx(key,"1");        } catch (Exception e) {            e.printStackTrace();        } finally {            jedis.close();        }        return -1L;    }    public static void expire(String key, int second) {        //此处假设已经拿到配置        JedisPoolConfig config = new JedisPoolConfig();        JedisPool pool = new JedisPool(config, ip, port, timeOut);        Jedis jedis = pool.getResource();        try {            jedis.expire(key, second);        } catch (Exception e) {            e.printStackTrace();        } finally {            jedis.close();        }    }    public static long del(String key) {        Jedis jedis = pool.getResource();        try {            return jedis.del(key);        } catch (Exception e) {            logger.error("codis异常:", e);        } finally {            jedis.close();        }        return 0;    }    public static long del(String key) {        Jedis jedis = pool.getResource();        try {            return jedis.del(key);        } catch (Exception e) {            logger.error("codis异常:", e);        } finally {            jedis.close();        }        return 0;    }}


(2) 使用inrr命令实现

public class InrrLockDemo {    private static final String KEY = "inrr.test";    private static final String ip = "xxxxxx";    private static final int port = 6379;    private static final int timeOut = 2000;    /**     * incr     * 根据key查找 判断是否存在 若不存在即设置为0+1 可以拿到锁,其他情况均得不到锁,     *外部调用可以根据boolean值得判断是否拿到锁     */    public static boolean inrrLock() {        Date now = new Date();        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        String date = sdf.format(now);        String cacheKey = String.format(KEY, date);        long i = incr(cacheKey);        //根据场景选择设置锁存在时间        expire(cacheKey, 3600 * 24);        return i == 1L;    }    public static long incr(String key) {        //此处假设已经拿到配置        JedisPoolConfig config = new JedisPoolConfig();        JedisPool pool = new JedisPool(config, ip, port, timeOut);        Jedis jedis = pool.getResource();        try {            return jedis.incr(key);        } catch (Exception e) {            e.printStackTrace();        } finally {            jedis.close();        }        return -1L;    }    public static void expire(String key, int second) {        //此处假设已经拿到配置        JedisPoolConfig config = new JedisPoolConfig();        JedisPool pool = new JedisPool(config, ip, port, timeOut);        Jedis jedis = pool.getResource();        try {            jedis.expire(key, second);        } catch (Exception e) {            e.printStackTrace();        } finally {            jedis.close();        }    }}




原创粉丝点击