发表于: 2018-02-28 23:37:01
1 643
今天完成的事情:
今天在学关于memcache的东西。
首先,在连接memcache服务器之前要事先搭建好memcache服务器,记住创建服务器的ip和端口号,使用java代码连接要使用ip和端口号。
然后在java中使用memcache的客户端,也就是jar包来对memcache服务器进行访问。
先创建memcache的工具类。
public class MemcachedUtil {
private static MemCachedClient cachedClient = new MemCachedClient();
static {
//获取连接池的实例
SockIOPool pool = SockIOPool.getInstance();
//服务器列表及其权重
String[] servers = {"127.0.0.1:11211"};
Integer[] weights = {3};
//设置服务器信息
pool.setServers(servers);
pool.setWeights(weights);
//设置初始连接数、最小连接数、最大连接数、最大处理时间
pool.setInitConn(10);
pool.setMinConn(10);
pool.setMaxConn(1000);
pool.setMaxIdle(1000 * 60 * 60);
//设置连接池守护线程的睡眠时间
pool.setMaintSleep(60);
//设置TCP参数,连接超时
pool.setNagle(false);
pool.setSocketTO(60);
pool.setSocketConnectTO(0);
//初始化并启动连接池
pool.initialize();
//压缩设置,超过指定大小的都压缩
// cachedClient.setCompressEnable(true);
// cachedClient.setCompressThreshold(1024*1024);
}
private MemcachedUtil() {
}
public static boolean add(String key, Object value) {
return cachedClient.add(key, value);
}
public static boolean add(String key, Object value, Integer expire) {
return cachedClient.add(key, value, expire);
}
public static boolean put(String key, Object value) {
return cachedClient.set(key, value);
}
public static boolean put(String key, Object value, Integer expire) {
return cachedClient.set(key, value, expire);
}
public static boolean replace(String key, Object value) {
return cachedClient.replace(key, value);
}
public static boolean replace(String key, Object value, Integer expire) {
return cachedClient.replace(key, value, expire);
}
public static Object get(String key) {
return cachedClient.get(key);
}
}
然厚创建memcache缓存的对象。但是因为数据传输的问题,缓存对象的创建需要序列化以后才能写入缓存、是实体类的话,就必须实现Serializable接口。
所以还需要创建序列化工具类:
public class SerializeUtil {
public static byte[] serizlize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (oos != null) {
oos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}
/*
* 反序列化
* */
public static Object deserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}
}
相关逻辑是:
读出数据库,序列化,写入缓存。
读出缓存,反序列化,传输给相应的对象。
关于memcache函数所有的方法列表如下:
明天计划的事情:尝试利用缓存搭建简单的项目。
遇到的问题:
1.尝试在memcache服务器写入值,但是不知道什么原因,返回的总是不理想。也想不出理由,放弃了。
收获:
对缓存系统有了一个比较深入的认识。
进度:今天学的比较少,一直找不到头绪、进度缓慢。
http://task.ptteng.com/zentao/project-task-490.html
评论