memcached client -- memcached client for java使用

来源:[url]http://blog.csdn.net/gtuu0123/article/details/4897805[/url]


memcached client for java是另一个memcached的java客户端

http://www.whalin.com/memcached/#download



代码:

(1)MemcachedServer -- memcached的服务器

[java] view plaincopyprint?
01.public class MemcachedServer {
02.
03. private String address;
04. private int port;
05. private int weight;
06.
07. public MemcachedServer(String address, int port, int weight) {
08. this.address = address;
09. this.port = port;
10. this.weight = weight;
11. }
12.
13. public String getAddress() {
14. return address;
15. }
16.
17. public int getPort() {
18. return port;
19. }
20.
21. public int getWeight() {
22. return weight;
23. }
24.
25. public String toString() {
26. return address + ":" + port + "," + weight;
27. }
28.
29.}
public class MemcachedServer {

private String address;
private int port;
private int weight;

public MemcachedServer(String address, int port, int weight) {
this.address = address;
this.port = port;
this.weight = weight;
}

public String getAddress() {
return address;
}

public int getPort() {
return port;
}

public int getWeight() {
return weight;
}

public String toString() {
return address + ":" + port + "," + weight;
}

}




(2)MemcachedException

[java] view plaincopyprint?
01.@SuppressWarnings("serial")
02.public class MemcachedException extends Exception {
03.
04. public MemcachedException() {
05. super();
06. }
07.
08. public MemcachedException(Throwable t) {
09. super(t);
10. }
11.
12. public MemcachedException(String error) {
13. super(error);
14. }
15.
16. public MemcachedException(String error, Throwable t) {
17. super(error, t);
18. }
19.
20.}
@SuppressWarnings("serial")
public class MemcachedException extends Exception {

public MemcachedException() {
super();
}

public MemcachedException(Throwable t) {
super(t);
}

public MemcachedException(String error) {
super(error);
}

public MemcachedException(String error, Throwable t) {
super(error, t);
}

}



(3)PoolDefaultProperties -- memcached池初始化参数

[java] view plaincopyprint?
01.import java.util.Properties;
02.
03.public class PoolDefaultProperties extends Properties {
04.
05. private static final long serialVersionUID = -7630655479181446040L;
06.
07. public PoolDefaultProperties() {
08. super();
09. initDefault();
10. }
11.
12. private void initDefault() {
13. initConn();
14. initMainSleep();
15. initTCP();
16. initFailover();
17. initAliveCheck();
18. }
19.
20. protected void initConn() {
21. setProperty("initConn", "10");
22. setProperty("minConn", "10");
23. setProperty("maxConn", "20");
24. setProperty("maxIdle", String.valueOf(1000 * 60 * 30));
25. }
26.
27. protected void initMainSleep() {
28. setProperty("maintSleep", String.valueOf(1000 * 5));
29. }
30.
31. protected void initTCP() {
32. setProperty("nagle", "false");
33. setProperty("socketTO", String.valueOf(1000 * 3));
34. setProperty("socketConnectTO", String.valueOf(1000 * 3));
35. }
36.
37. protected void initFailover() {
38. setProperty("failover", "true");
39. setProperty("failback", "true");
40. }
41.
42. protected void initAliveCheck() {
43. setProperty("aliveCheck", "true");
44. }
45.
46.}
import java.util.Properties;

public class PoolDefaultProperties extends Properties {

private static final long serialVersionUID = -7630655479181446040L;

public PoolDefaultProperties() {
super();
initDefault();
}

private void initDefault() {
initConn();
initMainSleep();
initTCP();
initFailover();
initAliveCheck();
}

protected void initConn() {
setProperty("initConn", "10");
setProperty("minConn", "10");
setProperty("maxConn", "20");
setProperty("maxIdle", String.valueOf(1000 * 60 * 30));
}

protected void initMainSleep() {
setProperty("maintSleep", String.valueOf(1000 * 5));
}

protected void initTCP() {
setProperty("nagle", "false");
setProperty("socketTO", String.valueOf(1000 * 3));
setProperty("socketConnectTO", String.valueOf(1000 * 3));
}

protected void initFailover() {
setProperty("failover", "true");
setProperty("failback", "true");
}

protected void initAliveCheck() {
setProperty("aliveCheck", "true");
}

}




(4)MemcachedPool -- memcached池

[java] view plaincopyprint?
01.import java.lang.reflect.InvocationTargetException;
02.import java.util.Iterator;
03.import java.util.List;
04.import java.util.Properties;
05.import java.util.Set;
06.
07.import org.apache.commons.beanutils.ConvertUtils;
08.import org.apache.commons.beanutils.PropertyUtils;
09.import org.apache.commons.logging.Log;
10.import org.apache.commons.logging.LogFactory;
11.
12.import com.danga.MemCached.SockIOPool;
13.
14.public class MemcachedPool {
15.
16. private static final Log logger = LogFactory.getLog(MemcachedPool.class);
17.
18. private static Properties POOL_DEFAULT_VALUE = new PoolDefaultProperties();
19.
20. private static MemcachedPool pool = new MemcachedPool();
21.
22. private MemcachedPool() {}
23.
24. public static MemcachedPool getInstance() {
25. return pool;
26. }
27.
28. public void initPool(List<MemcachedServer> servers) throws MemcachedException {
29. initPool(servers, POOL_DEFAULT_VALUE);
30. }
31.
32. public void initPool(List<MemcachedServer> servers, Properties props) throws MemcachedException {
33. SockIOPool sockIOPool = SockIOPool.getInstance();
34.
35. //server & weight
36. sockIOPool.setServers(getServer(servers));
37. sockIOPool.setWeights(getWeight(servers));
38.
39.
40. //bean props
41. Set keys = props.keySet();
42. Iterator keyIter = keys.iterator();
43. while (keyIter.hasNext()) {
44. String key = (String)keyIter.next();
45. String value = props.getProperty(key);
46. if (value == null) {
47. value = POOL_DEFAULT_VALUE.getProperty(key);
48. }
49. try {
50. Class type = PropertyUtils.getPropertyType(sockIOPool, key);
51. logger.debug("Type=" + type + ";Key=" + key + ";Value=" + value);
52. Object val = ConvertUtils.convert(value, type);
53. PropertyUtils.setSimpleProperty(sockIOPool, key, val);
54. } catch (IllegalAccessException e) {
55. throw new MemcachedException("Init Pool Fail", e);
56. } catch (InvocationTargetException e) {
57. throw new MemcachedException("Init Pool Fail", e);
58. } catch (NoSuchMethodException e) {
59. throw new MemcachedException("Init Pool Fail", e);
60. }
61. }
62. sockIOPool.initialize();
63. }
64.
65. private Integer[] getWeight(List<MemcachedServer> weigths) {
66. Integer[] w = new Integer[weigths.size()];
67. for (int i = 0; i < weigths.size(); i++) {
68. w[i] = weigths.get(i).getWeight();
69. }
70. return w;
71. }
72.
73. private String[] getServer(List<MemcachedServer> servers) {
74. String[] s = new String[servers.size()];
75. for (int i = 0; i < servers.size(); i++) {
76. MemcachedServer server = servers.get(i);
77. s[i] = server.getAddress() + ":" + server.getPort();
78. }
79. return s;
80. }
81.
82.
83.}
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.danga.MemCached.SockIOPool;

public class MemcachedPool {

private static final Log logger = LogFactory.getLog(MemcachedPool.class);

private static Properties POOL_DEFAULT_VALUE = new PoolDefaultProperties();

private static MemcachedPool pool = new MemcachedPool();

private MemcachedPool() {}

public static MemcachedPool getInstance() {
return pool;
}

public void initPool(List<MemcachedServer> servers) throws MemcachedException {
initPool(servers, POOL_DEFAULT_VALUE);
}

public void initPool(List<MemcachedServer> servers, Properties props) throws MemcachedException {
SockIOPool sockIOPool = SockIOPool.getInstance();

//server & weight
sockIOPool.setServers(getServer(servers));
sockIOPool.setWeights(getWeight(servers));


//bean props
Set keys = props.keySet();
Iterator keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = (String)keyIter.next();
String value = props.getProperty(key);
if (value == null) {
value = POOL_DEFAULT_VALUE.getProperty(key);
}
try {
Class type = PropertyUtils.getPropertyType(sockIOPool, key);
logger.debug("Type=" + type + ";Key=" + key + ";Value=" + value);
Object val = ConvertUtils.convert(value, type);
PropertyUtils.setSimpleProperty(sockIOPool, key, val);
} catch (IllegalAccessException e) {
throw new MemcachedException("Init Pool Fail", e);
} catch (InvocationTargetException e) {
throw new MemcachedException("Init Pool Fail", e);
} catch (NoSuchMethodException e) {
throw new MemcachedException("Init Pool Fail", e);
}
}
sockIOPool.initialize();
}

private Integer[] getWeight(List<MemcachedServer> weigths) {
Integer[] w = new Integer[weigths.size()];
for (int i = 0; i < weigths.size(); i++) {
w[i] = weigths.get(i).getWeight();
}
return w;
}

private String[] getServer(List<MemcachedServer> servers) {
String[] s = new String[servers.size()];
for (int i = 0; i < servers.size(); i++) {
MemcachedServer server = servers.get(i);
s[i] = server.getAddress() + ":" + server.getPort();
}
return s;
}


}




(5)MemcachedCli -- memcached操作客户端(只有set,get方法)

[java] view plaincopyprint?
01.import java.util.Date;
02.import java.util.Iterator;
03.import java.util.Map;
04.import java.util.Set;
05.
06.import com.danga.MemCached.MemCachedClient;
07.
08.public class MemcachedCli {
09.
10. private static MemcachedCli unique = new MemcachedCli();
11.
12. private MemcachedCli() {
13. init();
14. }
15.
16. public static MemcachedCli getInstance() {
17. return unique;
18. }
19.
20. private MemCachedClient client = new MemCachedClient();
21.
22. private void init() {
23. client.setPrimitiveAsString(true);
24. client.setCompressEnable(true);
25. client.setCompressThreshold(4 * 1024);
26. }
27.
28. public boolean set(String key, Object value) {
29. return client.set(key, value);
30. }
31.
32. public boolean set(String key, Object value, Date expired) {
33. return client.set(key, value, expired);
34. }
35.
36. public Object get(String key) {
37. return client.get(key);
38. }
39.
40. public void printStat() {
41. Map stats = client.stats();
42. Set keys = stats.keySet();
43. Iterator keyIter = keys.iterator();
44. while (keyIter.hasNext()) {
45. String key = (String)keyIter.next();
46. Object value = stats.get(key);
47. System.out.println(key + "=" + value);
48. }
49. }
50.
51.}
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.danga.MemCached.MemCachedClient;

public class MemcachedCli {

private static MemcachedCli unique = new MemcachedCli();

private MemcachedCli() {
init();
}

public static MemcachedCli getInstance() {
return unique;
}

private MemCachedClient client = new MemCachedClient();

private void init() {
client.setPrimitiveAsString(true);
client.setCompressEnable(true);
client.setCompressThreshold(4 * 1024);
}

public boolean set(String key, Object value) {
return client.set(key, value);
}

public boolean set(String key, Object value, Date expired) {
return client.set(key, value, expired);
}

public Object get(String key) {
return client.get(key);
}

public void printStat() {
Map stats = client.stats();
Set keys = stats.keySet();
Iterator keyIter = keys.iterator();
while (keyIter.hasNext()) {
String key = (String)keyIter.next();
Object value = stats.get(key);
System.out.println(key + "=" + value);
}
}

}




(6)MCTest -- 简单测试

[java] view plaincopyprint?
01.import java.util.ArrayList;
02.import java.util.List;
03.
04.public class MCTest {
05.
06. public static void main(String[] args) {
07. try {
08. MemcachedServer server = new MemcachedServer("localhost", 11211, 1);
09. List<MemcachedServer> servers = new ArrayList<MemcachedServer>();
10. servers.add(server);
11. MemcachedPool pool = MemcachedPool.getInstance();
12. pool.initPool(servers);
13. MemcachedCli client = MemcachedCli.getInstance();
14. String value = (String)client.get("test1");
15. System.out.println("value=" + value);
16. client.set("test1", "value1");
17. value = (String)client.get("test1");
18. System.out.println("value=" + value);
19. client.printStat();
20. } catch (MemcachedException e) {
21. e.printStackTrace();
22. }
23. }
24.
25.}
import java.util.ArrayList;
import java.util.List;

public class MCTest {

public static void main(String[] args) {
try {
MemcachedServer server = new MemcachedServer("localhost", 11211, 1);
List<MemcachedServer> servers = new ArrayList<MemcachedServer>();
servers.add(server);
MemcachedPool pool = MemcachedPool.getInstance();
pool.initPool(servers);
MemcachedCli client = MemcachedCli.getInstance();
String value = (String)client.get("test1");
System.out.println("value=" + value);
client.set("test1", "value1");
value = (String)client.get("test1");
System.out.println("value=" + value);
client.printStat();
} catch (MemcachedException e) {
e.printStackTrace();
}
}

}



测试运行结果,其中有memcached client包的调试信息:



com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ retrieving object and stuffing into a string.
value=value1
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ storing data as a string for key: test1 for class: java.lang.String
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ memcache cmd (result code): set test1 0 0 6
(STORED)
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ data successfully stored for key: test1
com.danga.MemCached.MemCachedClient Sun Nov 29 00:23:54 CST 2009 - ++++ retrieving object and stuffing into a string.
value=value1
localhost:11211={bytes_written=587, connection_structures=11, bytes=52, total_items=2, total_connections=21, uptime=284045336, pid=1416, get_hits=3, curr_items=1, version=1.2.1, cmd_get=4, time=1259425433, pointer_size=32, cmd_set=2, limit_maxbytes=67108864, bytes_read=162, curr_connections=10, get_misses=1}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值