当前位置:网站首页>Simple redis lock
Simple redis lock
2022-06-30 09:27:00 【Xiao Lu, a migrant worker in Beijing】
@Component
public class DistributedLock {
private static final Logger LOGGER = LoggerFactory.getLogger(DistributedLock.class);
@Resource(name = "cscRedisClient")
private RedisStoreClient redisStoreClient;
private static final String LOCK_CATEGORY = "oms_distribut_lock";
private static final String APP_KEY = "csc-oms-task-process-service";
/**
* Lock
* @param locaName The lock key
* @param acquireTimeout Get timeout
* @param timeout The timeout of the lock
* @return Lock logo
*/
public String lockWithTimeout(String locaName,
long acquireTimeout, int timeout) {
String retIdentifier = null;
try {
// Randomly generate one value
String identifier = UUID.randomUUID().toString();
// Lock name , namely key value
String lockKey = "lock:" + locaName;
// Timeout time , After locking, the lock will be released automatically
// int lockExpire = (int)(timeout / 1000);
// The timeout for obtaining the lock , After this time, the lock is abandoned
long end = System.currentTimeMillis() + acquireTimeout * 1000;
final StoreKey storeKey = new StoreKey(LOCK_CATEGORY, APP_KEY, lockKey);
while (System.currentTimeMillis() < end) {
if (redisStoreClient.setnx(storeKey, identifier)) {
redisStoreClient.expire(storeKey, timeout);
// return value value , Used to release lock time confirmation
retIdentifier = identifier;
return retIdentifier;
}
// return -1 representative key No timeout set , by key Set a timeout
if (redisStoreClient.ttl(storeKey) == -1) {
redisStoreClient.expire(storeKey, timeout);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (Exception e) {
LOGGER.error(" Lock acquisition failed " + locaName, e);
Cat.logError(" Lock acquisition failed " + locaName, e);
}
return retIdentifier;
}
/**
* Release the lock
* @param lockName The lock key
* @param identifier Release the lock logo
* @return
*/
public boolean releaseLock(String lockName, long acquireTimeout, String identifier) {
String lockKey = "lock:" + lockName;
boolean retFlag = false;
try {
final StoreKey storeKey = new StoreKey(LOCK_CATEGORY, APP_KEY, lockKey);
long end = System.currentTimeMillis() + acquireTimeout * 1000;
while (System.currentTimeMillis() < end) {
if (redisStoreClient.compareAndDelete(storeKey, identifier)) {
LOGGER.info("delelte lock");
break;
}
}
} catch (Exception e) {
LOGGER.warn("releaseLock,{}",e);
}
return retFlag;
}
}
边栏推荐
- Why must redis exist in distributed systems?
- JVM tuning related commands and explanations
- 7. know JNI and NDK
- Set, map and modularity
- Generate directory in markdown
- Express get request
- Research on lg1403 divisor
- The elegant combination of walle and Jianbao
- Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
- Talk about how the kotlin process started?
猜你喜欢

Summary of Android knowledge points and common interview questions

Use Huawei performance management service to configure the sampling rate on demand

Do you want the dialog box that pops up from the click?

The elegant combination of walle and Jianbao

Agp7.0|kts makes a reinforced plug-in

Abstract factory pattern

What kind of experience is it to develop a "grandson" who will call himself "Grandpa"?

Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)

9.JNI_ Necessary optimization design

Pit encountered by fastjason
随机推荐
Pit encountered by fastjason
Opencv learning notes -day2 (implemented by the color space conversion function cvtcolar(), and imwrite image saving function imwrite())
Script summary
Tclistener server and tcpclient client use -- socket listening server and socketclient use
Flutter theme (skin) changes
Torchvision loads the weight of RESNET except the full connection layer
[shutter] solve failed assertion: line 5142 POS 12: '_ debugLocked‘: is not true.
Rew acoustic test (V): equipment required for test
Esp32 (4): overview of the overall code architecture
Interpretation of source code demand:a rotation equivariant detector for aerial object detection
Evaluation standard for audio signal quality of intelligent speakers
Cronexpression expression explanation and cases
Code management related issues
Talking about kotlin process exception handling mechanism
Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)
C # get the current timestamp
Esp32 things (I): Preface
Deep Learning with Pytorch- A 60 Minute Blitz
What are the SQL add / delete / modify queries?
Esp32 (IX): OTA function of function development