当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢
spolicy请求案例
PMM (percona monitoring and management) installation record
Transform between tree and array in JS (hide the children field if the child node of the tree is empty)
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
Error in render: "typeerror: cannot read properties of undefined (reading 'length')" --- error when calling interface
Solve NPM -v sudden failure and no response
Flask framework beginner-03-template
[datawhale] [machine learning] Diabetes genetic risk detection challenge
数通基础-STP原理
2021 windows penetration of "Cyberspace Security" B module of Shandong secondary vocational group (analysis)
随机推荐
Netease cloud UI imitation -- & gt; sidebar
[fluorescent character effect]
Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install
Learning about opencv (3)
Error in render: "typeerror: cannot read properties of undefined (reading 'length')" --- error when calling interface
The use of MySQL in nodejs
Getting started with SQL - combined tables
Some descriptions of DS V2 push down in spark
Principle analysis and source code interpretation of service discovery
Set view dynamic picture
Mqtt x cli officially released: powerful and easy-to-use mqtt 5.0 command line tool
Write a script that can run in Bash / shell and PowerShell
Vectortilelayer replacement style
Okaleido ecological core equity Oka, all in fusion mining mode
Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market
Flask framework beginner-03-template
In Net 6.0
Network related journals and conferences in CS
B站这个视频我是跪着看完的
Interpretation of the standard of software programming level examination for teenagers_ second level