memcached client -- memcached client for java使用
来源:http://blog.csdn.net/gtuu0123/article/details/4897805
memcachedclientforjava是另一个memcached的java客户端
http://www.whalin.com/memcached/#download
代码:
(1)MemcachedServer--memcached的服务器
[java]viewplaincopyprint?
01.publicclassMemcachedServer{
02.
03.privateStringaddress;
04.privateintport;
05.privateintweight;
06.
07.publicMemcachedServer(Stringaddress,intport,intweight){
08.this.address=address;
09.this.port=port;
10.this.weight=weight;
11.}
12.
13.publicStringgetAddress(){
14.returnaddress;
15.}
16.
17.publicintgetPort(){
18.returnport;
19.}
20.
21.publicintgetWeight(){
22.returnweight;
23.}
24.
25.publicStringtoString(){
26.returnaddress+":"+port+","+weight;
27.}
28.
29.}
publicclassMemcachedServer{
privateStringaddress;
privateintport;
privateintweight;
publicMemcachedServer(Stringaddress,intport,intweight){
this.address=address;
this.port=port;
this.weight=weight;
}
publicStringgetAddress(){
returnaddress;
}
publicintgetPort(){
returnport;
}
publicintgetWeight(){
returnweight;
}
publicStringtoString(){
returnaddress+":"+port+","+weight;
}
}
(2)MemcachedException
[java]viewplaincopyprint?
01.@SuppressWarnings("serial")
02.publicclassMemcachedExceptionextendsException{
03.
04.publicMemcachedException(){
05.super();
06.}
07.
08.publicMemcachedException(Throwablet){
09.super(t);
10.}
11.
12.publicMemcachedException(Stringerror){
13.super(error);
14.}
15.
16.publicMemcachedException(Stringerror,Throwablet){
17.super(error,t);
18.}
19.
20.}
@SuppressWarnings("serial")
publicclassMemcachedExceptionextendsException{
publicMemcachedException(){
super();
}
publicMemcachedException(Throwablet){
super(t);
}
publicMemcachedException(Stringerror){
super(error);
}
publicMemcachedException(Stringerror,Throwablet){
super(error,t);
}
}
(3)PoolDefaultProperties--memcached池初始化参数
[java]viewplaincopyprint?
01.importjava.util.Properties;
02.
03.publicclassPoolDefaultPropertiesextendsProperties{
04.
05.privatestaticfinallongserialVersionUID=-7630655479181446040L;
06.
07.publicPoolDefaultProperties(){
08.super();
09.initDefault();
10.}
11.
12.privatevoidinitDefault(){
13.initConn();
14.initMainSleep();
15.initTCP();
16.initFailover();
17.initAliveCheck();
18.}
19.
20.protectedvoidinitConn(){
21.setProperty("initConn","10");
22.setProperty("minConn","10");
23.setProperty("maxConn","20");
24.setProperty("maxIdle",String.valueOf(1000*60*30));
25.}
26.
27.protectedvoidinitMainSleep(){
28.setProperty("maintSleep",String.valueOf(1000*5));
29.}
30.
31.protectedvoidinitTCP(){
32.setProperty("nagle","false");
33.setProperty("socketTO",String.valueOf(1000*3));
34.setProperty("socketConnectTO",String.valueOf(1000*3));
35.}
36.
37.protectedvoidinitFailover(){
38.setProperty("failover","true");
39.setProperty("failback","true");
40.}
41.
42.protectedvoidinitAliveCheck(){
43.setProperty("aliveCheck","true");
44.}
45.
46.}
importjava.util.Properties;
publicclassPoolDefaultPropertiesextendsProperties{
privatestaticfinallongserialVersionUID=-7630655479181446040L;
publicPoolDefaultProperties(){
super();
initDefault();
}
privatevoidinitDefault(){
initConn();
initMainSleep();
initTCP();
initFailover();
initAliveCheck();
}
protectedvoidinitConn(){
setProperty("initConn","10");
setProperty("minConn","10");
setProperty("maxConn","20");
setProperty("maxIdle",String.valueOf(1000*60*30));
}
protectedvoidinitMainSleep(){
setProperty("maintSleep",String.valueOf(1000*5));
}
protectedvoidinitTCP(){
setProperty("nagle","false");
setProperty("socketTO",String.valueOf(1000*3));
setProperty("socketConnectTO",String.valueOf(1000*3));
}
protectedvoidinitFailover(){
setProperty("failover","true");
setProperty("failback","true");
}
protectedvoidinitAliveCheck(){
setProperty("aliveCheck","true");
}
}
(4)MemcachedPool--memcached池
[java]viewplaincopyprint?
01.importjava.lang.reflect.InvocationTargetException;
02.importjava.util.Iterator;
03.importjava.util.List;
04.importjava.util.Properties;
05.importjava.util.Set;
06.
07.importorg.apache.commons.beanutils.ConvertUtils;
08.importorg.apache.commons.beanutils.PropertyUtils;
09.importorg.apache.commons.logging.Log;
10.importorg.apache.commons.logging.LogFactory;
11.
12.importcom.danga.MemCached.SockIOPool;
13.
14.publicclassMemcachedPool{
15.
16.privatestaticfinalLoglogger=LogFactory.getLog(MemcachedPool.class);
17.
18.privatestaticPropertiesPOOL_DEFAULT_VALUE=newPoolDefaultProperties();
19.
20.privatestaticMemcachedPoolpool=newMemcachedPool();
21.
22.privateMemcachedPool(){}
23.
24.publicstaticMemcachedPoolgetInstance(){
25.returnpool;
26.}
27.
28.publicvoidinitPool(List<MemcachedServer>servers)throwsMemcachedException{
29.initPool(servers,POOL_DEFAULT_VALUE);
30.}
31.
32.publicvoidinitPool(List<MemcachedServer>servers,Propertiesprops)throwsMemcachedException{
33.SockIOPoolsockIOPool=SockIOPool.getInstance();
34.
35.//server&weight
36.sockIOPool.setServers(getServer(servers));
37.sockIOPool.setWeights(getWeight(servers));
38.
39.
40.//beanprops
41.Setkeys=props.keySet();
42.IteratorkeyIter=keys.iterator();
43.while(keyIter.hasNext()){
44.Stringkey=(String)keyIter.next();
45.Stringvalue=props.getProperty(key);
46.if(value==null){
47.value=POOL_DEFAULT_VALUE.getProperty(key);
48.}
49.try{
50.Classtype=PropertyUtils.getPropertyType(sockIOPool,key);
51.logger.debug("Type="+type+";Key="+key+";Value="+value);
52.Objectval=ConvertUtils.convert(value,type);
53.PropertyUtils.setSimpleProperty(sockIOPool,key,val);
54.}catch(IllegalAccessExceptione){
55.thrownewMemcachedException("InitPoolFail",e);
56.}catch(InvocationTargetExceptione){
57.thrownewMemcachedException("InitPoolFail",e);
58.}catch(NoSuchMethodExceptione){
59.thrownewMemcachedException("InitPoolFail",e);
60.}
61.}
62.sockIOPool.initialize();
63.}
64.
65.privateInteger[]getWeight(List<MemcachedServer>weigths){
66.Integer[]w=newInteger[weigths.size()];
67.for(inti=0;i<weigths.size();i++){
68.w[i]=weigths.get(i).getWeight();
69.}
70.returnw;
71.}
72.
73.privateString[]getServer(List<MemcachedServer>servers){
74.String[]s=newString[servers.size()];
75.for(inti=0;i<servers.size();i++){
76.MemcachedServerserver=servers.get(i);
77.s[i]=server.getAddress()+":"+server.getPort();
78.}
79.returns;
80.}
81.
82.
83.}
importjava.lang.reflect.InvocationTargetException;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Properties;
importjava.util.Set;
importorg.apache.commons.beanutils.ConvertUtils;
importorg.apache.commons.beanutils.PropertyUtils;
importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importcom.danga.MemCached.SockIOPool;
publicclassMemcachedPool{
privatestaticfinalLoglogger=LogFactory.getLog(MemcachedPool.class);
privatestaticPropertiesPOOL_DEFAULT_VALUE=newPoolDefaultProperties();
privatestaticMemcachedPoolpool=newMemcachedPool();
privateMemcachedPool(){}
publicstaticMemcachedPoolgetInstance(){
returnpool;
}
publicvoidinitPool(List<MemcachedServer>servers)throwsMemcachedException{
initPool(servers,POOL_DEFAULT_VALUE);
}
publicvoidinitPool(List<MemcachedServer>servers,Propertiesprops)throwsMemcachedException{
SockIOPoolsockIOPool=SockIOPool.getInstance();
//server&weight
sockIOPool.setServers(getServer(servers));
sockIOPool.setWeights(getWeight(servers));
//beanprops
Setkeys=props.keySet();
IteratorkeyIter=keys.iterator();
while(keyIter.hasNext()){
Stringkey=(String)keyIter.next();
Stringvalue=props.getProperty(key);
if(value==null){
value=POOL_DEFAULT_VALUE.getProperty(key);
}
try{
Classtype=PropertyUtils.getPropertyType(sockIOPool,key);
logger.debug("Type="+type+";Key="+key+";Value="+value);
Objectval=ConvertUtils.convert(value,type);
PropertyUtils.setSimpleProperty(sockIOPool,key,val);
}catch(IllegalAccessExceptione){
thrownewMemcachedException("InitPoolFail",e);
}catch(InvocationTargetExceptione){
thrownewMemcachedException("InitPoolFail",e);
}catch(NoSuchMethodExceptione){
thrownewMemcachedException("InitPoolFail",e);
}
}
sockIOPool.initialize();
}
privateInteger[]getWeight(List<MemcachedServer>weigths){
Integer[]w=newInteger[weigths.size()];
for(inti=0;i<weigths.size();i++){
w[i]=weigths.get(i).getWeight();
}
returnw;
}
privateString[]getServer(List<MemcachedServer>servers){
String[]s=newString[servers.size()];
for(inti=0;i<servers.size();i++){
MemcachedServerserver=servers.get(i);
s[i]=server.getAddress()+":"+server.getPort();
}
returns;
}
}
(5)MemcachedCli--memcached操作客户端(只有set,get方法)
[java]viewplaincopyprint?
01.importjava.util.Date;
02.importjava.util.Iterator;
03.importjava.util.Map;
04.importjava.util.Set;
05.
06.importcom.danga.MemCached.MemCachedClient;
07.
08.publicclassMemcachedCli{
09.
10.privatestaticMemcachedCliunique=newMemcachedCli();
11.
12.privateMemcachedCli(){
13.init();
14.}
15.
16.publicstaticMemcachedCligetInstance(){
17.returnunique;
18.}
19.
20.privateMemCachedClientclient=newMemCachedClient();
21.
22.privatevoidinit(){
23.client.setPrimitiveAsString(true);
24.client.setCompressEnable(true);
25.client.setCompressThreshold(4*1024);
26.}
27.
28.publicbooleanset(Stringkey,Objectvalue){
29.returnclient.set(key,value);
30.}
31.
32.publicbooleanset(Stringkey,Objectvalue,Dateexpired){
33.returnclient.set(key,value,expired);
34.}
35.
36.publicObjectget(Stringkey){
37.returnclient.get(key);
38.}
39.
40.publicvoidprintStat(){
41.Mapstats=client.stats();
42.Setkeys=stats.keySet();
43.IteratorkeyIter=keys.iterator();
44.while(keyIter.hasNext()){
45.Stringkey=(String)keyIter.next();
46.Objectvalue=stats.get(key);
47.System.out.println(key+"="+value);
48.}
49.}
50.
51.}
importjava.util.Date;
importjava.util.Iterator;
importjava.util.Map;
importjava.util.Set;
importcom.danga.MemCached.MemCachedClient;
publicclassMemcachedCli{
privatestaticMemcachedCliunique=newMemcachedCli();
privateMemcachedCli(){
init();
}
publicstaticMemcachedCligetInstance(){
returnunique;
}
privateMemCachedClientclient=newMemCachedClient();
privatevoidinit(){
client.setPrimitiveAsString(true);
client.setCompressEnable(true);
client.setCompressThreshold(4*1024);
}
publicbooleanset(Stringkey,Objectvalue){
returnclient.set(key,value);
}
publicbooleanset(Stringkey,Objectvalue,Dateexpired){
returnclient.set(key,value,expired);
}
publicObjectget(Stringkey){
returnclient.get(key);
}
publicvoidprintStat(){
Mapstats=client.stats();
Setkeys=stats.keySet();
IteratorkeyIter=keys.iterator();
while(keyIter.hasNext()){
Stringkey=(String)keyIter.next();
Objectvalue=stats.get(key);
System.out.println(key+"="+value);
}
}
}
(6)MCTest--简单测试
[java]viewplaincopyprint?
01.importjava.util.ArrayList;
02.importjava.util.List;
03.
04.publicclassMCTest{
05.
06.publicstaticvoidmain(String[]args){
07.try{
08.MemcachedServerserver=newMemcachedServer("localhost",11211,1);
09.List<MemcachedServer>servers=newArrayList<MemcachedServer>();
10.servers.add(server);
11.MemcachedPoolpool=MemcachedPool.getInstance();
12.pool.initPool(servers);
13.MemcachedCliclient=MemcachedCli.getInstance();
14.Stringvalue=(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(MemcachedExceptione){
21.e.printStackTrace();
22.}
23.}
24.
25.}
importjava.util.ArrayList;
importjava.util.List;
publicclassMCTest{
publicstaticvoidmain(String[]args){
try{
MemcachedServerserver=newMemcachedServer("localhost",11211,1);
List<MemcachedServer>servers=newArrayList<MemcachedServer>();
servers.add(server);
MemcachedPoolpool=MemcachedPool.getInstance();
pool.initPool(servers);
MemcachedCliclient=MemcachedCli.getInstance();
Stringvalue=(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(MemcachedExceptione){
e.printStackTrace();
}
}
}
测试运行结果,其中有memcachedclient包的调试信息:
com.danga.MemCached.MemCachedClientSunNov2900:23:54CST2009-++++retrievingobjectandstuffingintoastring.
value=value1
com.danga.MemCached.MemCachedClientSunNov2900:23:54CST2009-++++storingdataasastringforkey:test1forclass:java.lang.String
com.danga.MemCached.MemCachedClientSunNov2900:23:54CST2009-++++memcachecmd(resultcode):settest1006
(STORED)
com.danga.MemCached.MemCachedClientSunNov2900:23:54CST2009-++++datasuccessfullystoredforkey:test1
com.danga.MemCached.MemCachedClientSunNov2900:23:54CST2009-++++retrievingobjectandstuffingintoastring.
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}