1.memcached client for java
客戶端API:memcached client for java
網址:http://www.whalin.com/memcached
最新版本:java_memcached-release_2.0.1
操作示例:
Java代碼
import com.danga.MemCached.*;
import org.apache.log4j.*;
public class TestMemcached {
public static void main(String[] args) {
/*初始化SockIOPool,管理memcached的連接池*/
String[] servers = { "192.168.1.20:12111" };
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(servers);
pool.setFailover(true);
pool.setInitConn(10);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaintSleep(30);
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setAliveCheck(true);
pool.initialize();
/*建立MemcachedClient實例*/
MemCachedClient memCachedClient = new MemCachedClient();
for (int i = 0; i < 10; i++) {
/*將對象加入到memcached緩存*/
boolean success = memCachedClient.set("" + i, "Hello!");
/*從memcached緩存中按key值取對象*/
String result = (String) memCachedClient.get("" + i);
System.out.println(String.format("set( %d ): %s", i, success));
System.out.println(String.format("get( %d ): %s", i, result));
}
}
}
2.spymemcached
客戶端API:spymemcached client
網址:http://code.google.com/p/spymemcached/
最新版本:memcached-2.1.jar
操作示例:用spymemcached將對象存入緩存
Java代碼
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import net.spy.memcached.MemcachedClient;
public class MClient {
public static void main(String[] args){
try{
/*建立MemcachedClient 實例,並指定memcached服務的IP地址和端口號*/
MemcachedClient mc = new MemcachedClient(new InetSocketAddress("192.168.1.20", 12111));
Future<Boolean> b = null;
/*將key值,過期時間(秒)和要緩存的對象set到memcached中*/
b = mc.set("neea:testDaF:ksIdno", 900, "someObject");
if(b.get().booleanValue()==true){
mc.shutdown();
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
用spymemcached從緩存中取得對象
Java代碼
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import net.spy.memcached.MemcachedClient;
public class MClient {
public static void main(String[] args){
try{
/*建立MemcachedClient 實例,並指定memcached服務的IP地址和端口號*/
MemcachedClient mc = new MemcachedClient(new InetSocketAddress("192.168.1.20", 12111));
/*按照key值從memcached中查找緩存,不存在則返回null */
Object b = mc.get("neea:testDaF:ksIdno ");
mc.shutdown();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
3.兩種API比較
memcached client for java:較早推出的memcached JAVA客戶端API,應用廣泛,運行比較穩定。
spymemcached:A simple, asynchronous, single-threaded memcached client written in java. 支持異步,單線程的memcached客戶端,用到了java1.5版本的concurrent和nio,存取速度會高於前者,但是穩定性不好,測試中常報timeOut等相關異常。
由於memcached client for java發布了新版本,性能上有所提高,並且運行穩定,所以建議使用memcached client for java.