-
Notifications
You must be signed in to change notification settings - Fork 314
/
Copy pathZkReentrantLockTemplateTest.java
81 lines (71 loc) · 3.13 KB
/
ZkReentrantLockTemplateTest.java
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
71
72
73
74
75
76
77
78
79
80
81
package com.distributed.lock.zk;
import com.distributed.lock.Callback;
import com.distributed.lock.redis.RedisDistributedLockTemplate;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Test;
import redis.clients.jedis.JedisPool;
import java.util.concurrent.*;
/**
* Created by [email protected] on 2016/2/24.
*/
public class ZkReentrantLockTemplateTest {
@Test
public void testTry() throws InterruptedException {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
client.start();
final ZkDistributedLockTemplate template=new ZkDistributedLockTemplate(client);
int size=100;
final CountDownLatch startCountDownLatch = new CountDownLatch(1);
final CountDownLatch endDownLatch=new CountDownLatch(size);
for (int i =0;i<size;i++){
new Thread() {
public void run() {
try {
startCountDownLatch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
final int sleepTime=ThreadLocalRandom.current().nextInt(5)*1000;
template.execute("test",5000, new Callback() {
public Object onGetLock() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + ":getLock");
Thread.currentThread().sleep(sleepTime);
System.out.println(Thread.currentThread().getName() + ":sleeped:"+sleepTime);
endDownLatch.countDown();
return null;
}
public Object onTimeout() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + ":timeout");
endDownLatch.countDown();
return null;
}
});
}
}.start();
}
startCountDownLatch.countDown();
endDownLatch.await();
}
public static void main(String[] args){
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
client.start();
final ZkDistributedLockTemplate template=new ZkDistributedLockTemplate(client);//本类多线程安全,可通过spring注入
template.execute("订单流水号", 5000, new Callback() {
@Override
public Object onGetLock() throws InterruptedException {
//TODO 获得锁后要做的事
return null;
}
@Override
public Object onTimeout() throws InterruptedException {
//TODO 获得锁超时后要做的事
return null;
}
});
}
}