Redis 分布式锁

参考🔗,该文解释的很详细,非常👍 Redis 分布式锁的正确实现方式( Java 版 )

记录我的实际应用Code,redis的连接要随时释放哦


import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * @author 醉卧花海听萧
 * @date 2019/5/6
 */
@Slf4j
@Component
public class SpaceRedisService {

    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";

    @Resource(name = "redisTemplate1")
    private RedisTemplate redisTemplate1;

    public Boolean lock(String key, String requestId, long expireTime) {
        RedisConnection conn = RedisConnectionUtils.getConnection(redisTemplate1.getConnectionFactory());
        Jedis jedis = (Jedis) conn.getNativeConnection();
        try {
            String result = jedis.set(key, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
            if (LOCK_SUCCESS.equals(result)) {
                return true;
            }
        } catch (Exception e) {
            log.error("--LOCK ERROR:", e);
        } finally {
            RedisConnectionUtils.releaseConnection(conn, redisTemplate1.getConnectionFactory());
        }
        return false;
    }

    public Boolean unLock(String key, String requestId) {
        RedisConnection conn = RedisConnectionUtils.getConnection(redisTemplate1.getConnectionFactory());
        Jedis jedis = (Jedis) conn.getNativeConnection();
        try {
            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(key), Collections.singletonList(requestId));
            if (RELEASE_SUCCESS.equals(result)) {
                return true;
            }
        } catch (Exception e) {
            log.error("--UNLOCK ERROR:", e);
        } finally {
            RedisConnectionUtils.releaseConnection(conn, redisTemplate1.getConnectionFactory());
        }
        return false;
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 分布式锁一般有三种实现方式:1. 数据库乐观锁;2. 基于Redis的分布式锁;3. 基于ZooKeeper...
    朦胧蜜桃阅读 3,332评论 1 0
  • 前言 分布式锁一般有三种实现方式:1. 数据库乐观锁;2. 基于Redis的分布式锁;3. 基于ZooKeeper...
    真老根儿阅读 5,075评论 2 38
  • 世界上从来没有吵赢的架了,但遇到情况还不能不吵架,一吵架双方心情都不好,这是我们生活当中不可逃避的事实,那么为什么...
    三层天的奥秘阅读 4,629评论 3 40
  • 轻轻的风轻轻的吹来, 拂扬着你的细发 风儿调皮的探出手掌 在你的发丝间摩挲打闹 舞动着灵动与欢快 雨落后的清晨 小...
    雨下茶南阅读 1,300评论 0 0