Use spy and memcached for java to operate memcache
I. spy
Package com. test. memcache;
Import java.net. InetSocketAddress;
Import java. util. concurrent. Future;
Import net. spy. memcached. MemcachedClient;
/**
* The package used in this class is a memcached-2.4.1.jar
*: Http://code.google.com/p/spymemcached/
*/
Public class SpyTest {
Public void putObject (){
Try {
/* Create a MemcachedClient instance and specify the IP address and port number of the memcached Service */
MemcachedClient mc = new MemcachedClient (new InetSocketAddress ("127.0.0.1", 11211 ));
Future <Boolean> B = null;
/* Set the key value, expiration time (in seconds), and object to be cached to memcached */
B = mc. set ("key1", 60, "hello1"); // if it exists previously, it will automatically Overwrite
If (B. get (). booleanValue () = true ){
Mc. shutdown ();
}
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}
Public void getObject (){
Try {
/* Create a MemcachedClient instance and specify the IP address and port number of the memcached Service */
MemcachedClient mc = new MemcachedClient (new InetSocketAddress ("127.0.0.1", 11211 ));
/* Query the cache from memcached based on the key value. If no cache exists, null is returned */
Object B = mc. get ("key1 ");
System. out. println (B );
Mc. shutdown ();
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}
Public static void main (String [] args ){
}
}
Ii. memcached for java
Package com. test. memcache;
Import com. danga. MemCached. MemCachedClient;
Import com. danga. MemCached. SockIOPool;
/**
* This class uses a java_memcached-release-2.5.1.jar package
*: Http://github.com/gwhalin/Memcached-Java-Client/downloads
*
* @ Author Administrator
*
*/
Public class MemcachedTest {
String [] servers = {"127.0.0.1: 11211 "};
Integer [] weights = {3 };
MemCachedClient mcc = new MemCachedClient ();
// Create an instance object SockIOPool
SockIOPool pool = SockIOPool. getInstance ();
Public MemcachedTest (){
Pool. setServers (servers );
Pool. setWeights (weights );
Pool. setInitConn (5 );
Pool. setMinConn (5 );
Pool. setMaxConn (250 );
Pool. setMaxIdle (30 );
Pool. setMaintSleep (30 );
Pool. initialize ();
}
Public void putObject (){
For (int I = 1; I <10; I ++ ){
Boolean B = mcc. add ("key" + I, "hi, michael" + I); // if it exists before, it is not updated.
System. out. println ("key" + I + B );
}
}
Public void replaceObject (){
Boolean B = mcc. replace ("key2", "hi, tom"); // if the key does not exist, flase is returned. update failed.
System. out. println ("update" + B );
}
Public void getObject (){
Object obj = mcc. get ("key2 ");
System. out. println (obj );
}
Public static void main (String args []) {
MemcachedTest tc = new MemcachedTest ();
// Tc. putObject ();
// Tc. replaceObject ();
Tc. getObject ();
Tc. pool. shutDown ();
}
}