一、Redis分布式锁实现思路

Redis实现分布式锁基于SetNx命令,因为在redis中key是保证是唯一的。所以当多个线程同时创建setNx时,只要谁能够创建成功谁就能获取到锁。

Set命令:每次set时,可以修改原来旧值;

SetNx命令:每次SetNx检查key是否已经存在,如果已经存在的话就不会执行任何操作,返回0;反之,新增该key。

获取锁的时候:当多个线程同时创建SetNx key,只要谁能够创建成功谁就能够获取到锁。

释放锁:可以对该key设置一个有效期可以避免死锁的现象。

二、Zookeeper实现分布式锁思路

Zookeeper实现分布式锁核心采用临时节点+事件通知,因为Zookeeper节点路径是保证全局唯一的,当多个线程同时创建该临时节点,只要谁能够创建成功谁就能获取到锁。

获取锁:当多个线程同时创建该临时节点,只要谁能够创建成功谁就能够获取到锁。

释放锁:关闭当前Session连接,自动的删除当前的zk节点路径,其他线程重新进入到获取锁阶段。

三、分布式锁应用场景

  1. 分布式任务调度平台保证任务的幂等性。

  2. 分布式全局id的生成

四、Redis分布式锁核心代码

public class RedisUtil {
    //protected static Logger logger = Logger.getLogger(RedisUtil.class);
    
    private static String IP = "192.168.75.128";

    //Redis的端口号
    private static int PORT = 6379;

    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 100;

    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = 20;

    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    private static int MAX_WAIT = 3000;

    private static int TIMEOUT = 3000;

    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = true;

    //在return给pool时,是否提前进行validate操作;
    private static boolean TEST_ON_RETURN = true;

    private static JedisPool jedisPool = null;

    /**
     * redis过期时间,以秒为单位
     */
    public final static int EXRP_HOUR = 60 * 60; //一小时
    public final static int EXRP_DAY = 60 * 60 * 24; //一天
    public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月

    /**
     * 初始化Redis连接池
     */
    private static void initialPool() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);

            jedisPool = new JedisPool(config, IP, PORT, TIMEOUT, "123456");
        } catch (Exception e) {
            //logger.error("First create JedisPool error : "+e);
            e.getMessage();
        }
    }


    /**
     * 在多线程环境同步初始化
     */
    private static synchronized void poolInit() {
        if (jedisPool == null) {
            initialPool();
        }
    }


    /**
     * 同步获取Jedis实例
     *
     * @return Jedis
     */
    public synchronized static Jedis getJedis() {
        if (jedisPool == null) {
            poolInit();
        }
        Jedis jedis = null;
        try {
            if (jedisPool != null) {
                jedis = jedisPool.getResource();
            }
        } catch (Exception e) {
            e.getMessage();
            // logger.error("Get jedis error : "+e);
        }
        return jedis;
    }


    /**
     * 释放jedis资源
     *
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedisPool.returnResource(jedis);
        }
    }

    public static Long sadd(String key, String... members) {
        Jedis jedis = null;
        Long res = null;
        try {
            jedis = getJedis();
            res = jedis.sadd(key, members);
        } catch (Exception e) {
            //logger.error("sadd  error : "+e);
            e.getMessage();
        }
        return res;
    }
}

    public class RedisLock {

    private static final int setnxSuccss = 1;

    /**
     * 获取锁
     *
     * @param lockKey        定义锁的key
     * @param notLockTimeOut 没有获取锁的超时时间
     * @param lockTimeOut    使用锁的超时时间
     * @return
     */
    public String getLock(String lockKey, int notLockTimeOut, int lockTimeOut) {
        // 获取Redis连接
        Jedis jedis = RedisUtil.getJedis();
        // 定义没有获取锁的超时时间
        Long endTimeOut = System.currentTimeMillis() + notLockTimeOut;
        while (System.currentTimeMillis() < endTimeOut) {
            String lockValue = UUID.randomUUID().toString();
            // 如果在多线程情况下谁能够setnx 成功返回0 谁就获取到锁
            if (jedis.setnx(lockKey, lockValue) == setnxSuccss) {
                jedis.expire(lockKey, lockTimeOut / 1000);
                return lockValue;
            }
            // 否则情况下 在超时时间内继续循环
        }
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 释放锁 其实就是将该key删除
     *
     * @return
     */
    public Boolean unLock(String lockKey, String lockValue) {
        Jedis jedis = RedisUtil.getJedis();
        // 确定是对应的锁 ,才删除
        if (lockValue.equals(jedis.get(lockKey))) {
            return jedis.del(lockKey) > 0 ? true : false;
        }
        return false;
    }
}
public class TestService {

    private RedisLock redisLock = new RedisLock();
    private String lockKey = "redis_lock";

    public void service() {
        // 1.获取锁
        String lockValue = redisLock.getLock(lockKey, 5000, 5000);
        if (StringUtils.isEmpty(lockValue)) {
            System.out.println(Thread.currentThread().getName() + ",获取锁失败!");
            return;
        }
        // 2.获取锁成功执行业务逻辑
        System.out.println(Thread.currentThread().getName() + ",获取成功,lockValue:" + lockValue);
        // 3.释放lock锁
        redisLock.unLock(lockKey, lockValue);
    }
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

Redis 自动过期机制 上一篇
Redis持久化机制 下一篇