当前位置:网站首页>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;
}
}
边栏推荐
- Coredata acquisition in swift sorting, ascending, descending
- 桂林 穩健醫療收購桂林乳膠100%股權 填補乳膠產品線空白
- Find the number that appears only once in the array
- POJ 1753 flip game (DFS 𞓜 bit operation)
- 4. use ibinder interface flexibly for short-range communication
- Esp32 (6): Bluetooth and WiFi functions for function development
- Opencv learning notes -day10 logical operation of image pixels (usage of rectangle function and rect function and bit related operation in openCV)
- Guilin robust medical acquired 100% equity of Guilin Latex to fill the blank of latex product line
- ACM intensive training graph theory exercise 3 in the summer vacation of 2020 [problem solving]
- Use V-IF with V-for
猜你喜欢
Tutorial for beginners of small programs day01
Sort (simple description)
Dart asynchronous task
Solution to the eighth training competition of 2020 Provincial Games
Implementing custom drawer component in quick application
7. know JNI and NDK
Baidu map JS browsing terminal
Interviewer: do you understand the principle of recyclerview layout animation?
MySQL-- Entity Framework Code First(EF Code First)
Esp32 (4): overview of the overall code architecture
随机推荐
Opencv learning notes -day 12 (ROI region extraction and inrange() function operation)
Reading notes of "Introduction to deep learning: pytoch"
Implementing custom drawer component in quick application
Tutorial for beginners of small programs day01
Esp32 (4): overview of the overall code architecture
ES6 learning path (III) deconstruction assignment
Rew acoustic test (VI): signal and measurement
Why must redis exist in distributed systems?
About Lombok's @data annotation
[cmake] make command cannot be executed normally
Row column (vertical and horizontal table) conversion of SQL
Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
Electron, which can wrap web page programs into desktop applications
Explanation on the use of password profiteering cracking tool Hydra
Rew acoustic test (I): microphone calibration
Small program learning path 1 - getting to know small programs
桂林 稳健医疗收购桂林乳胶100%股权 填补乳胶产品线空白
Summary of Android knowledge points and common interview questions
Rew acoustic test (III): generate test signal
Differences between the notify(), notifyall(), notifydatasetchanged(), notifydatasetinvalidated() methods in the adapter