当前位置:网站首页>Redis realizes distributed lock and gets a watchdog
Redis realizes distributed lock and gets a watchdog
2022-07-26 10:14:00 【Whale-52 Hz】
redis Distributed lock + watchdog
because redis Cluster in CAP In theory, it belongs to AP, So if it is a very strict distributed locking scenario .redis It's not very suitable for .
When the task execution time cannot be estimated ,expireTime Parameter passing -1. Will use a watchdog , Until the task releases the lock .
redis Lock tool :
import lombok.experimental.UtilityClass;
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.StringRedisSerializer;
import java.util.Collections;
/** * redis Lock tool * * @Author: dong * @Date: 2021/11/19 13:41 */
@UtilityClass
public class RedisLockUtil {
private static final Long SUCCESS = 1L;
private RedisTemplate redisTemplate;
/** * Try to get distributed lock utilize redis set It's worth it NX Parameters * @param lockKey lock (key) * @param requestId Lock owner identification (value) * @param expireTime Beyond the time second * @return */
public boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime){
String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
boolean beginDog = false;
if(expireTime==-1){
expireTime = LockWatchdog.lockWatchdogTimeout;
beginDog = true;
}
Object result = redisTemplate.execute(redisScript,new StringRedisSerializer(),new StringRedisSerializer(),
Collections.singletonList(lockKey),requestId,expireTime + "");
boolean equals = SUCCESS.equals(result);
if(equals&&beginDog){
LockWatchdog.beginLockWatchdog(lockKey,requestId);
}
return equals;
}
/** * Release distributed lock utilize LUA Scripts guarantee the atomicity of operations (Redis Single process, single thread and guaranteed execution LUA Script without executing other commands ) * @param lockKey lock (key) * @param requestId Lock owner identification (value) * @return */
public boolean releaseDistributedLock(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";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Object result = redisTemplate.execute(redisScript,new StringRedisSerializer(),new StringRedisSerializer(),
Collections.singletonList(lockKey), requestId);
return SUCCESS.equals(result);
}
}
watchdog
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
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.StringRedisSerializer;
import java.util.Collections;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
/** * Redis Lock the watchdog * * @Author: dong * @Date: 2021/12/7 15:11 */
@Slf4j
@UtilityClass
public class LockWatchdog {
private Timer TIMER = new Timer();
public int lockWatchdogTimeout = 30;
private RedisTemplate redisTemplate;
/** * Open a watchdog *@Author dong *@Date 2021/12/7 15:14 *@param lockKey *@return */
public void beginLockWatchdog(String lockKey,String val){
renewExpiration(lockKey,val);
}
/** * Extend the lock expiration time *@Author dong *@Date 2021/12/7 15:06 *@param *@return */
private void renewExpiration(String lockKey,String val){
TIMER.schedule(new TimerTask() {
@Override
public void run() {
try {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('expire', KEYS[1], ARGV[2]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Object result = redisTemplate.execute(redisScript,new StringRedisSerializer(),new StringRedisSerializer(),
Collections.singletonList(lockKey),val,String.valueOf(lockWatchdogTimeout));
if(Objects.equals(result,1L)){
renewExpiration(lockKey,val);
}
}catch (Exception e){
log.error("redis Lock extension failed !",e);
}
}
},lockWatchdogTimeout*1000 / 3L);
}
}
边栏推荐
- Flask框架初学-04-flask蓝图及代码抽离
- 输入整数后输入整行字符串的解决方法
- The practice of OpenCV -- bank card number recognition
- 在.NET 6.0中配置WebHostBuilder
- Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install
- Spolicy request case
- Wechat applet learning notes 2
- Wechat H5 payment on WAP, for non wechat browsers
- Solution of inputting whole line string after inputting integer
- [MySQL database] a collection of basic MySQL operations - the basis of seeing (adding, deleting, modifying, and querying)
猜你喜欢

Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)

30分钟彻底弄懂 synchronized 锁升级过程

AirTest

Flask框架初学-04-flask蓝图及代码抽离

Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component

Uniapp error 7 < Map >: marker ID should be a number

Uni app learning summary

Mysql5.7.25 master-slave replication (one-way)

Production of a-modal drag function in antui

服务发现原理分析与源码解读
随机推荐
spolicy请求案例
Interview shock 68: why does TCP need three handshakes?
输入整数后输入整行字符串的解决方法
如何写一篇百万阅读量的文章
Reproduce the snake game in C language (I) build pages and construct snakes
Draw arrows with openlayer
Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)
Mqtt x cli officially released: powerful and easy-to-use mqtt 5.0 command line tool
Matlab Simulink realizes fuzzy PID control of time-delay temperature control system of central air conditioning
I finished watching this video on my knees at station B
[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks
What is the principle of reflection mechanism?
Solution of inputting whole line string after inputting integer
Show default image when wechat applet image cannot be displayed
Flutter event distribution
Study notes of the first week of sophomore year
Flutter Event 派发
Usage of the formatter attribute of El table
Encapsulation of tabbarcontroller
AirTest