当前位置:网站首页>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);
}
}
边栏推荐
- 数通基础-二层交换原理
- The charm of SQL optimization! From 30248s to 0.001s
- Matlab Simulink realizes fuzzy PID control of time-delay temperature control system of central air conditioning
- Mqtt x cli officially released: powerful and easy-to-use mqtt 5.0 command line tool
- Okaleido ecological core equity Oka, all in fusion mining mode
- IE7 set overflow attribute failure solution
- Installation and use of cocoapods
- Leetcode 504. 七进制数
- SQL优化的魅力!从 30248s 到 0.001s
- Interview shock 68: why does TCP need three handshakes?
猜你喜欢
Beginner of flask framework-04-flask blueprint and code separation
Node memory overflow and V8 garbage collection mechanism
面试突击68:为什么 TCP 需要 3 次握手?
Solve NPM -v sudden failure and no response
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
Okaleido生态核心权益OKA,尽在聚变Mining模式
protobuf的基本用法
[qualcomm][network] QTI service analysis
点赞,《新程序员》电子书限时免费领啦!
Mysql5.7.25 master-slave replication (one-way)
随机推荐
SQL优化的魅力!从 30248s 到 0.001s
如何写一篇百万阅读量的文章
输入整数后输入整行字符串的解决方法
反射机制的原理是什么?
Due to fierce competition in the new market, China Mobile was forced to launch a restrictive ultra-low price 5g package
30分钟彻底弄懂 synchronized 锁升级过程
Study notes of the second week of sophomore year
Sqoop [put it into practice 02] sqoop latest version full database import + data filtering + field type support description and example code (query parameter and field type forced conversion)
Learning about opencv (2)
数通基础-STP原理
分布式网络通信框架:本地服务怎么发布成RPC服务
汉诺塔II|汉诺塔4柱
在.NET 6.0中配置WebHostBuilder
The use of MySQL in nodejs
SQL Server 2008 R2 installation problems
Data communication foundation TCPIP reference model
PHP one-time request lifecycle
Study notes of the first week of sophomore year
Learning about tensor (III)
Draw arrows with openlayer