memcached應用隨筆
Memcached 是一個高性能的分布式內存對象緩存系統,用于動態Web應用以減輕數據庫負載。相信大家對它并不陌生,下面把我最近開發的項目中用到的一個例子分享出來,給大家一起學習。在訪問memcached時,通過synchronized實現同步。在需要操作memcached的地方可以很方便地通過類CacheFactory進行。廢話少說,直接貼上代碼。
1
import org.apache.log4j.BasicConfigurator;
2
import org.apache.log4j.Logger;
3
4
5
import com.danga.MemCached.MemCachedClient;
6
import com.danga.MemCached.SockIOPool;
7
8
9
/**
10
* memcache工廠類
11
*
12
* @author fengyue
13
* @date Feb 16, 2011
14
*/
15
public class CacheFactory {
16
private static final Logger logger = Logger.getLogger(CacheFactory.class);
17
private static MemCachedClient memcache = null;
18
19
20
public static MemCachedClient getCache() {
21
if (memcache == null) {
22
synchronized (CacheFactory.class) {
23
if (memcache == null)
24
getInstance();
25
}
26
}
27
28
29
return memcache;
30
}
31
32
33
private static void getInstance() {
34
try {
35
BasicConfigurator.configure();
36
String serverI = "10.185.23.17:13000";
37
String[] servers = { serverI };
38
SockIOPool pool = SockIOPool.getInstance();
39
pool.setServers(servers);
40
pool.setFailover(true);
41
pool.setInitConn(10);
42
pool.setMinConn(5);
43
pool.setMaxConn(250);
44
pool.setMaintSleep(30);
45
pool.setNagle(false);
46
pool.setSocketTO(3000);
47
48
49
pool.initialize();
50
memcache = new MemCachedClient();
51
memcache.add("test", "test1111111111111111111");
52
53
54
} catch (Exception e) {
55
logger.debug("failed to init memcache
");
56
e.printStackTrace();
57
}
58
}
59
60
61
62
63
public static void main(String[] argvs) {
64
//往memcache存入緩存值
65
CacheFactory.getCache().set("myloginkey“, "1", new Date(3 * 60 * 60 * 1000));
66
//取出值
67
CacheFactory.getCache().get("myloginkey");
68
//刪除
69
CacheFactory.getCache().delete("myloginkey");
70
return;
71
}
72
}

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

posted on 2011-11-24 14:07 風悅 閱讀(1784) 評論(0) 編輯 收藏 引用 所屬分類: Java