码迷,mamicode.com
首页 > 编程语言 > 详细

spring data redis分布式锁

时间:2020-01-16 10:31:21      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:单机   执行时间   redis分布式   redist   ogg   就是   boolean   info   lis   

问题

项目采用spring-boot-starter-data-redis,RedisTemplate中没有同时设置NX和EX的方法,如果使用setIfAbsent()方法也就是NX,再设置过期时间expire()也就是EX,如果在设置EX时失败则会造成死锁。在jedis中提供了同时设置NX和EX的方法,这里通过RedisTemplate的execute()方法获取Jedis。

存在问题

解决方案可以可以参考Redisson

  1. 哨兵模式下有问题,Master挂了可能没有复制到Slave导致锁丢失
  2. 如果是多个系统redis配置的库不同会有问题
  3. 因为是不公平锁,所以可能会出现饥饿的情况
  4. 不支持重入
  5. 如果执行时间大于锁过期时间,则会破坏原子性

实现

public class RedisLockUtil {
    private static Logger log = LoggerFactory.getLogger(RedisLockUtil.class);
    private static final String LOCK_SUCCESS = "OK";
    private static final Long RELEASE_SUCCESS = 1L;
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";

    private RedisTemplate redisTemplate;
    /**
     * 分布式锁的键值
     */
    private String lockKey;

    /**
     * 锁的超时时间 10s
     */
    int expireTime = 10 * 1000;

    /**
     * 锁等待,防止线程饥饿 1s
     */
    int acquireTimeout = 5 * 1000;

    /**
     * 获取指定键值的锁
     *
     * @param lockKey 锁的键值
     */
    public RedisLockUtil(RedisTemplate redisTemplate, String lockKey) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey;
    }

    /**
     * 获取指定键值的锁,同时设置获取锁超时时间
     *
     * @param lockKey        锁的键值
     * @param acquireTimeout 获取锁超时时间
     */
    public RedisLockUtil(RedisTemplate redisTemplate, String lockKey, int acquireTimeout) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey;
        this.acquireTimeout = acquireTimeout;
    }

    /**
     * 获取指定键值的锁,同时设置获取锁超时时间和锁过期时间
     *
     * @param lockKey        锁的键值
     * @param acquireTimeout 获取锁超时时间
     * @param expireTime     锁失效时间
     */
    public RedisLockUtil(RedisTemplate redisTemplate, String lockKey, int acquireTimeout, int expireTime) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey;
        this.acquireTimeout = acquireTimeout;
        this.expireTime = expireTime;
    }

    public String acquire() {
        try {
            // 获取锁的超时时间,超过这个时间则放弃获取锁
            long end = System.currentTimeMillis() + acquireTimeout;
            // 随机生成一个value
            SnowflakeIdWorkerUtils idWorker = new SnowflakeIdWorkerUtils(0, 1);
            String requireToken = idWorker.nextId();
            while (System.currentTimeMillis() < end) {
                String result = (String) redisTemplate.execute((RedisCallback<String>) connection -> {
                    Jedis jedis =  (Jedis)connection.getNativeConnection();
                    return jedis.set(lockKey, requireToken, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
                });

                if (LOCK_SUCCESS.equals(result)) {
                    return requireToken;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        } catch (Exception e) {
            log.error("acquire lock due to error", e);
        }

        return null;
    }

    public boolean release(String identify) {
        if (identify == null) {
            return false;
        }
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = new Object();
        try {
            result = redisTemplate.execute((RedisCallback<Long>) connection -> {
                Jedis jedis =  (Jedis)connection.getNativeConnection();
                return (Long) jedis.eval(script, Collections.singletonList(lockKey),
                        Collections.singletonList(identify));
            });
            if (RELEASE_SUCCESS.equals(result)) {
                log.info("release lock success, requestToken:{}", identify);
                return true;
            }
        } catch (Exception e) {
            log.error("release lock due to error", e);
        }
        log.info("release lock failed, requestToken:{}, result:{}", identify, result);
        return false;
    }
}

参考

Redis官方文档
Redisson java分布式锁实现
单机分布式锁
集群布式锁

spring data redis分布式锁

标签:单机   执行时间   redis分布式   redist   ogg   就是   boolean   info   lis   

原文地址:https://www.cnblogs.com/ingxx/p/12199636.html

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