-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisDistributedLock.java
More file actions
70 lines (57 loc) · 1.54 KB
/
RedisDistributedLock.java
File metadata and controls
70 lines (57 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.xycode.distributed;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* @author xycode
*/
@Slf4j
public class RedisDistributedLock implements Lock {
private String lockName;
private Jedis cli;
public RedisDistributedLock(String lockName) {
this.lockName = lockName;
cli = new Jedis("121.48.165.121", 7777);
cli.auth("pass");
}
@Override
public void lock() {
while (true) {
if (tryLock()) {
break;
} else {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("{} waiting for redis lock", Thread.currentThread().getName());
}
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public boolean tryLock() {
if (cli.setnx(lockName, "lock") == 1) {
return true;
}
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public void unlock() {
cli.del(lockName);
log.info("{} released redis lock", Thread.currentThread().getName());
}
@Override
public Condition newCondition() {
return null;
}
}