package com.unionbigdata.rdc.maindata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;
import java.util.Collections;
/**
* TODO
*
* @Author Leo
* @Date 2021/12/22 17:26
*/
@Component
@Slf4j
public class DistributedLock {
public static final long FAIL = 0L;
public static final long SUCCESS = 1L;
@Autowired
private RedisTemplate redisTemplate;
/**
* 加锁
* @param key 键
* @param requestId 请求id用以释放锁
* @param expireTime 超时时间(秒)
* @return
*/
public boolean getDistributedLock(String key, String requestId, long expireTime) {
String script = "if redis.call('setNx',KEYS[1],ARGV[1]) == 1 then if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end else return 0 end";
Object result = executeRedisScript(script, key, requestId, expireTime);
return result != null && result.equals(SUCCESS);
}
/**
* 释放锁
* @param key 键
* @param requestId 请求id用以释放锁
* @return
*/
public boolean releaseDistributedLock(String key, 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 = executeRedisScript(script, key, requestId);
return result != null && result.equals(SUCCESS);
}
/**
*
* @param script 脚本字符串
* @param key 键
* @param args 脚本其他参数
* @return
*/
public Object executeRedisScript(String script, String key, Object... args) {
try {
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
return redisTemplate.execute(redisScript, Collections.singletonList(key), args);
} catch (Exception e) {
log.error( "executeRedisScript script ececute error:", e);
return FAIL;
}
}
}
基于SpringBoot与Redis实现分布式锁
最新推荐文章于 2024-08-01 02:10:00 发布