Redis分布式锁的正确姿势

1. 核心代码:

import redis.clients.jedis.Jedis;import java.util.Collections;public class RedisUtil {    private static final String LOCK_SUCCESS = "OK";    private static final String SET_IF_NOT_EXIST = "NX";    private static final String SET_WITH_EXPIRE_TIME = "PX";    private static final Long RELEASE_SUCCESS = 1L;    /**     * redis分布式锁的加锁操作     *     * @param jedis     * @param lockKey     * @param requestId     * @param expireTime     * @return     */    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);        if (LOCK_SUCCESS.equals(result)) {            return true;        }        return false;    }    /**     * redis分布式锁的解锁操作     *     * @param jedis     * @param lockKey     * @param requestId     * @return     */    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {        String script = "if redis.call(‘get‘, KEYS[1]) == ARGV[1] then return redis.call(‘del‘, KEYS[1]) else return 0 end";        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));        if (RELEASE_SUCCESS.equals(requestId))            return true;        return false;    }}

2. 代码解释:

分布式锁的加锁和解锁必须是同一个人,锁必须有过期时间。lua脚本执行是为了保证一致性。

3. 学习总结:

Redis 可以实现分布式锁,Zookeeper(临时的有序队列)也可以实现分布式锁,数据库也可以实现分布式锁。

Redis分布式锁的正确姿势

4. 参考文档:

https://www.cnblogs.com/williamjie/p/9395659.html