spring data redis分布式锁

Posted ingxx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring data redis分布式锁相关的知识,希望对你有一定的参考价值。

问题

项目采用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. 如果执行时间大于锁过期时间,则会破坏原子性

实现

package com.bailian.scloud.util;

import com.bailian.scloud.service.impl.CloudMbBasicInfoServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * @program: scloud-support
 * @description: Redis锁
 * 不完美可以参考
 * @see <a href=https://redis.io/topics/distlock)/>
 * @see <a href=https://github.com/redisson/redisson/>
 * @author: weijiankai
 * @create: 2020-01-15 15:25
 **/
//TODO  可以参考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;

    /**
     * 锁等待,防止线程饥饿 10s
     */
    int acquireTimeout = 20 * 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) {
                //获取jedis客户端,原因redisTemplate没有同时是指NX和EX的方法
                String result = (String) redisTemplate.execute((RedisCallback<String>) connection -> {
                    JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                    return commands.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 -> {
                Object nativeConnection = connection.getNativeConnection();
                //集群模式
                if (nativeConnection instanceof JedisCluster) {
                    return (Long) ((JedisCluster) nativeConnection).eval(script, Collections.singletonList(lockKey),
                            Collections.singletonList(identify));
                }// 单机模式
                else if (nativeConnection instanceof Jedis) {
                    return (Long) ((Jedis) nativeConnection).eval(script, Collections.singletonList(lockKey),
                            Collections.singletonList(identify));
                }else {
                    return 0L;
                }
            });
            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学习系列--JedisPool与spring集成的实现及一致性哈希分析和基于Redis的分布式锁

Spring整合Redis分布式锁

Spring Boot (33) 分布式锁

Redis实现分布式锁(设计模式应用实战)

Redis实现分布式锁(设计模式应用实战)

redis实现分布式锁