当前位置:网站首页>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);
}
}
边栏推荐
- On the compilation of student management system of C language course (simple version)
- Principle analysis and source code interpretation of service discovery
- Force deduction DFS
- Wechat applet learning notes 2
- 服务器内存故障预测居然可以这样做!
- Flask框架初学-03-模板
- AirTest
- [award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks
- What is the principle of reflection mechanism?
- Interpretation of the standard of software programming level examination for teenagers_ second level
猜你喜欢

The charm of SQL optimization! From 30248s to 0.001s

点赞,《新程序员》电子书限时免费领啦!

数通基础-网络基础知识

2022 zhongkepan cloud - server internal information acquisition and analysis flag
![[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks](/img/0f/01d6e49fff80a325b667784e40bff3.png)
[award-winning question] ask Judea pearl, the Turing prize winner and the father of Bayesian networks

Session based recommendations with recurrent neural networks

数通基础-STP原理

Learning about opencv (3)

Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market

Uni app learning summary
随机推荐
在.NET 6.0中配置WebHostBuilder
Docker configuring MySQL Cluster
面试突击68:为什么 TCP 需要 3 次握手?
数通基础-二层交换原理
Error in render: "typeerror: cannot read properties of undefined (reading 'length')" --- error when calling interface
MySQL function
Set view dynamic picture
Use of selectors
万字详解“用知识图谱驱动企业业绩增长”
Sqoop [environment setup 01] CentOS Linux release 7.5 installation configuration sqoop-1.4.7 resolve warnings and verify (attach sqoop 1 + sqoop 2 Latest installation package +mysql driver package res
Learning about opencv (4)
[Qualcomm][Network] qti服务分析
[information system project manager] summary of essence of high-level series for the first time
Session based recommendations with recurrent neural networks
Like, "new programmer" e-book is free for a limited time!
Study notes of the first week of sophomore year
Getting started with SQL - combined tables
Vs2019 configuring opencv
Uniapp common error [wxml file compilation error]./pages/home/home Wxml and using MySQL front provided by phpstudy to establish an independent MySQL database and a detailed tutorial for independent da
Data communication foundation - layer 2 switching principle