用spy和memcached for java兩種方式對memcache進行操作
一、spy
package com.test.memcache;
import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import net.spy.memcached.MemcachedClient;
/**
* 本類用的包是memcached-2.4.1.jar
* : http://code.google.com/p/spymemcached/
*/
public class SpyTest {
public void putObject() {
try {
/* 建立MemcachedClient 執行個體,並指定memcached服務的IP地址和連接埠號碼 */
MemcachedClient mc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
Future<Boolean> b = null;
/* 將key值,到期時間(秒)和要緩衝的對象set到memcached中 */
b = mc.set("key1", 60, "hello1"); // 如果以前存在,則會自動覆蓋
if (b.get().booleanValue() == true) {
mc.shutdown();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void getObject() {
try {
/* 建立MemcachedClient 執行個體,並指定memcached服務的IP地址和連接埠號碼 */
MemcachedClient mc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
/* 按照key值從memcached中尋找緩衝,不存在則返回null */
Object b = mc.get("key1");
System.out.println(b);
mc.shutdown();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
}
}
二、memcached for java
package com.test.memcache;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/**
* 本類用的是java_memcached-release-2.5.1.jar包
* : 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();
// 建立一個執行個體對象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); // 如果以前存在,則不去更新
System.out.println("key" + i + b);
}
}
public void replaceObject() {
Boolean b = mcc.replace("key2", "hi, tom"); // 如果key不存在,則返回flase,更新失敗
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();
}
}