memcache并没有想象的那么复杂,就把他想成一个数据库就可以。以下是我的简单操作,第一次写文章,欢迎大家zhidao:
1.安装memcache客户端和服务端(网上下载资源好多)
2.创建连接,并操作memcache
public class MemcacheDetail {
// 构建缓存客户端
private static MemCachedClient cachedClient;
// 单例模式实现客户端管理类
private static MemcacheDetail INSTANCE = new MemcacheDetail();
private MemcacheDetail() {
cachedClient = new MemCachedClient();
//获取连接池实例
SockIOPool pool = SockIOPool.getInstance();
//设置缓存服务器地址,可以设置多个实现分布式缓存
pool.setServers(new String[]{"127.0.0.1:11211"});
//设置初始连接5
pool.setInitConn(5);
//设置最小连接5
pool.setMinConn(5);
//设置最大连接250
pool.setMaxConn(250);
//设置每个连接最大空闲时间3个小时
pool.setMaxIdle(1000 * 60 * 60 * 3);
pool.setMaintSleep(30);
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
pool.initialize();
}
public static MemcacheDetail getInstance() {
return INSTANCE;
}
public void add(String key, Object value) {
cachedClient.set(key, value);
}
public void add(String key, Object value, int milliseconds) {
cachedClient.set(key, value, milliseconds);
}
public void remove(String key) {
cachedClient.delete(key);
}
public void remove(String key, int milliseconds) {
cachedClient.delete(key, milliseconds, new Date());
}
public void update(String key, Object value, int milliseconds) {
cachedClient.replace(key, value, milliseconds);
}
public void update(String key, Object value) {
cachedClient.replace(key, value);
}
public Object get(String key) {
return cachedClient.get(key);
}
}
3.memcache下存放对象,cache中只能存放序列化的对象,才能再次调用得到:
public class DemoObject implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1845199006809045268L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
存放对象:
MemcacheDetail INSTANCE = MemcacheDetail.getInstance();
DemoObject ss = new DemoObject();
ss.setName(effict);
INSTANCE.add(effict, ss);
获取对象:
MemcacheDetail INSTANCE = MemcacheDetail.getInstance();
DemoObject ss = (DemoObject) INSTANCE.get(ww);