这篇文章主要讲解了“redis分布式锁的用法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“redis分布式锁的用法”吧!
没什么技术含量,不想写的直接拷贝了用吧 ????
基于SpringDataRedis
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* @author : xuchonggao
* @since : 2019-10-11
*/
@Component
public class RedisLock {
@Resource
StringRedisTemplate stringRedisTemplate;
private RedisLock() {
}
/**
* redis 锁
*
* @param key 要锁定的key
* @param waitTime 获取锁的等待时间 阻塞时间
* @param expireTime 锁过期时间 默认10s
* @return
*/
public boolean lock(String key, Duration waitTime, Duration expireTime) {
if (StringUtils.isBlank(key)) {
return false;
}
long start = System.currentTimeMillis();
long waitTimeMillis = waitTime != null ? waitTime.toMillis() : 0L;
if (expireTime == null) {
expireTime = Duration.ofSeconds(10);
}
do {
Boolean lockRes = stringRedisTemplate.opsForValue().setIfAbsent(key, StringUtils.EMPTY, expireTime);
if (Boolean.TRUE.equals(lockRes)) {
return true;
}
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException ignore) {
}
} while (System.currentTimeMillis() - start < waitTimeMillis);
return false;
}
/**
* redis 锁
* 非阻塞
*
* @param key 要锁定的key
* @param expireTime 锁过期时间
* @return
*/
public boolean lock(String key, Duration expireTime) {
return lock(key, null, expireTime);
}
/**
* redis 锁
* 默认十秒过期 非阻塞
*
* @param key 要锁定的key
* @return
*/
public boolean lock(String key) {
return lock(key, null, null);
}
/**
* 解锁
*
* @param key
*/
public void unlock(String key) {
stringRedisTemplate.delete(key);
}
}
感谢各位的阅读,以上就是“redis分布式锁的用法”的内容了,经过本文的学习后,相信大家对redis分布式锁的用法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/razox/blog/3116335