// 设置初始连接数、最小、最大连接数以及最大处理时间
pool.setInitConn(5);
pool.setMinConn(5);
pool.setMaxConn(250);
pool.setMaxIdle(1000 * 60 * 60 * 6);
// 设置主线程的睡眠时间
pool.setMaintSleep(30);
// 设置TCP的参数,连接超时等
pool.setNagle(false);
pool.setSocketTO(3000);
pool.setSocketConnectTO(0);
// 初始化连接池
pool.initialize();
// 设置序列化,因为java的基本类型不支持序列化,在确定cache的数据类型是string的情况下设为true,可以加快处理速度
memCachedClient.setPrimitiveAsString(true);
}
public Object get(String key) {
return memCachedClient.get(key);
}
public static MemcachedUtil getInstance() {
return memcachedUtil;
}
//如果key不存在,就增加,如果存在,就覆盖
public boolean add(String key, Object value) {
return memCachedClient.add(key, value);
}
public boolean add(String key, Object value, Date expiryDate) {
return memCachedClient.add(key, value, expiryDate);
}
//如果key不存在,报错
public boolean replace(String key, Object value) {
return memCachedClient.replace(key, value);
}
public boolean replace(String key, Object value, Date expiry) {
return memCachedClient.replace(key, value, expiry);
}
public boolean delete(String key){
return memCachedClient.delete(key);
}
public boolean delete(String key, Date expiry){
return memCachedClient.delete(key, expiry);
}
public boolean delete (String key, Integer hashCode, Date expiry){
return memCachedClient.delete(key, hashCode, expiry);
}
//如果key存在,则失败
public boolean set(String key,Object value){
return memCachedClient.set(key, value);
}
public boolean set(String key,Object value,Integer hashCode){
return memCachedClient.set(key, value, hashCode);
}
//cache计数
public boolean storeCounter(String key,long value){
return memCachedClient.storeCounter(key, value);
}
public long incr(String key,long value){
return memCachedClient.incr(key, value);
}
//根据多个key获取对象
public Map<String,Object> getObjects(String[] keys){
return memCachedClient.getMulti(keys);
}
//清空对象
public boolean flush(){
return memCachedClient.flushAll();
}
//清空缓存对象,servers表示批量清空哪些机器的缓存
public boolean flushBaseTime(String[] servers){
return memCachedClient.flushAll(servers);
}
//获取服务器状态
public Map<String,Map<String,String>> getStats(){
return memCachedClient.stats();
}
//获取各个slab里item的数量
public Map<String,Map<String,String>> getStatsItem(){
return memCachedClient.statsItems();
}
}
实体类:
package com.memcached.vo;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String userId;
private String userName;
private String adder;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAdder() {
return adder;
}
public void setAdder(String adder) {
this.adder = adder;
}
}
分别运行后结果如下:
test():
从缓存中获取数据:memcached
123
张三
重庆
testDelete():
从缓存中获取数据:memcached
再次从缓存中获取数据:null
testReplace():
从缓存中获取数据:memcached
第一次从缓存里面获取user:123
再次从缓存中获取数据:replaceId
testGetStats():