forked from zxiaofan/JavaUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisUtilTest.java
More file actions
64 lines (54 loc) · 1.64 KB
/
RedisUtilTest.java
File metadata and controls
64 lines (54 loc) · 1.64 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
package utils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.zxiaofan.util.rpc.RedisUtil;
import junit.framework.TestCase;
/**
*
* @author zxiaofan
*/
public class RedisUtilTest extends TestCase {
String keyR = "key1"; // 对指定key操作
int num = 500; // 多线程自增次数
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
incr(keyR);
} catch (Exception e) {
e.printStackTrace();
}
}
};
/**
* 并发测试(多线程多同一key自增).
*
* 证明:Redis是单线程的,对redis的操作都是具有原子性的,是线程安全的操作。
*
* @throws Exception
*/
public void testConcurrency() throws Exception {
RedisUtil.set(keyR, "0");
// System.out.print(RedisUtil.getValue(keyR) + "-->");
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < num; i++) {
service.execute(runnable);
}
service.shutdown();
while (!service.isTerminated()) {
Thread.sleep(1000);
}
assertEquals("" + num, RedisUtil.get(keyR));
}
/**
* 循环自增(务必加锁).
*
* @param key
* 自增key
* @throws Exception
* 异常
*/
private synchronized static void incr(String key) throws Exception {
RedisUtil.set(key, String.valueOf(Integer.valueOf(RedisUtil.get(key)) + 1));
}
}