当前位置:网站首页>redis实现分布式锁
redis实现分布式锁
2022-06-22 00:28:00 【温温top】
package com.demo.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Component
public class LockUtil {
@Autowired
RedisTemplate<String, String> redisTemplate;
/**
* 获取锁的默认超时时间
*/
private static final long timeout = 300;
/**
* 加锁,无阻塞
* @param key
* @param expireTime 加锁锁时间
* @return
*/
public Boolean lock(String key, long expireTime) {
String requestId = UUID.randomUUID().toString();
Long start = System.currentTimeMillis();
//自旋,在一定时间内获取锁,超时则返回错误
for (; ; ) {
//Set命令返回OK,则证明获取锁成功
Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, requestId, expireTime,
TimeUnit.SECONDS);
if (ret) {
return true;
}
//否则循环等待,在timeout时间内仍未获取到锁,则获取失败
long end = System.currentTimeMillis() - start;
if (end >= timeout) {
return false;
}
}
}
/**
* 加锁,无阻塞
* @param key
* @param expireTime 加锁锁时间 秒
* @param waitTime 等待时间 毫秒
* @return
*/
public boolean lock(String key, long expireTime, long waitTime) {
String value = "trade_task";
long start = System.currentTimeMillis();
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
// 自旋,在一定时间内获取锁,超时则返回错误
for (; ; ) {
//Set命令返回OK,则证明获取锁成功
Boolean ret = opsForValue.setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
if (ret != null && ret) {
return true;
}
//否则循环等待,在timeout时间内仍未获取到锁,则获取失败
long end = System.currentTimeMillis() - start;
if (end >= waitTime) {
return false;
}
}
}
public void unlock(String key) {
redisTemplate.delete(key);
}
}
边栏推荐
- 记录webscraper的使用过程
- Pytorch learning 10: statistical operations
- matplotlib 制作不等间距直方图
- Counter完之后,想统计字符串长度大于2的结果
- Differences among active window, focused window and foreground window
- 3746. 牛的学术圈 II
- Sending webhook of message queue to realize cross application asynchronous callback
- 容器云是什么意思?与堡垒机有什么区别?
- field. setAccessible(true); Code scanning has security vulnerability, solution
- 【环境踩坑】No module named ‘PyQt5‘
猜你喜欢

对“基于tensorflow+RNN的新浪新闻文本分类”一文的图示化理解

Pytorch learning 08: splicing and splitting

编译原理-递归下降子程序法

動態規劃-01背包,分割等和子集,最後一塊石頭的重量

Tensorflow environment setup
![3 minutes, take you to play with chat robot automation [top template]](/img/71/4d848b46a52b71a351a086db248a95.png)
3 minutes, take you to play with chat robot automation [top template]

Pytorch learning 12: automatic derivation

0x00007ffff3d3ecd0 in _ IO_ vfprintf_ internal (s=0x7ffff40b5620 <_IO_2_1_stdout_>

Compilation principle - recursive descent subroutine method
![[cyw20189] VII. Detailed explanation of HCI command format](/img/ba/c61d4868e6c5da8460541c62649880.png)
[cyw20189] VII. Detailed explanation of HCI command format
随机推荐
Precautions for using timestamp type of SQLite3 database
Pytorch learning 10: statistical operations
Compilation principle - recursive descent subroutine method
What does container cloud mean? What is the difference with fortress machine?
The appearance, space, safety and power are all upgraded. The xinjietu x70s will be put on the market from 87900 yuan
【环境踩坑】在自己电脑上搭建FastDFS
Idea prompt duplicated code fragment (15 lines long)
Idea prompt 'optional Get() 'without' ispresent() 'check error.
2. add two numbers
[dailyfresh] course record 3 -- product search related
Find find files with different extensions
三种文件句柄之间的转换
【DailyFresh】发送激活邮件遇到的问题
HDOJ - Is It A Tree?
颜值、空间、安全、动力齐升级,新捷途X70S 8.79万元起售上市
Tables and table structures related to the flowable runtime transaction
Sparkrdd case: calculate total score
Pytorch learning 04: creation of tensor
Evc4 program cannot run on the emulator
[gstreamer] plug in writing - Test Program