源代码下载地址:http://www.zuidaima.com/share/1550463754996736.htm
参考地址:
http://www.open-open.com/lib/view/open1357831114183.html
http://tech.idv2.com/2008/07/10/memcached-001/
感谢 京-java牛-ID号1 感谢 锡-SuperPrivate-195
在网上搜索了部分代码,一个很简单的Demo,将查询的结果集存入缓存。我也不是太懂,大家可以搜索下资料,不过加入MemCached后项目访问速度的确增加了
package com.dream.core.util;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/**
* @describe:MemoryUtil.java
*
* @date 2013-9-30
* @author yuanlin.su www.zuidaima.com
* 参考地址:http://www.open-open.com/lib/view/open1357831114183.html
* http://tech.idv2.com/2008/07/10/memcached-001/
* 感谢 京-java牛-ID号1
* 感谢 锡-SuperPrivate-195
*
* 服务端和jar包免积分下载地址:http://download.csdn.net/detail/consuy/6341989
*/
public class MemoryUtil {
private static MemCachedClient client = null;
private final static String CACHE_ISOPEN_KEY = "CACHE_ISOPEN";
/**
* 初始化MEMCACHE工具
*/
public synchronized static void init(String ipAddress) {
if (client == null) {
String[] servers = { ipAddress };
Integer[] weights = { 1 };
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(servers);
pool.setWeights(weights);
pool.setNagle(false);
pool.setSocketTO(10000);
pool.setSocketConnectTO(3000);
pool.initialize();
client = new MemCachedClient();
set(CACHE_ISOPEN_KEY, 1);
}
}
/**
* 设置值
*
* @param key
* @param value
*/
public static void set(String key, Object value) {
client.set(key, value);
}
/**
* 设置值同时添加有效期
*
* @param key
* @param value
* @param minute 分钟
*/
public static void set(String key, Object value, int minute) {
client.set(key, value, new Date(System.currentTimeMillis() + minute * 60 * 1000l));
}
/**
* 检查值是否存在
*
* @param key
* @return
*/
public static boolean keyExists(String key) {
return client.keyExists(key);
}
/**
* 删除内存数据项的值
*
* @param key
*/
public static void delete(String key) {
client.delete(key);
}
/**
* 清空所有的数据
*/
public static void clear() {
client.flushAll();
}
/**
* 从内存中查询对象信息
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
return (T) client.get(key);
}
/**
* 判断MEMCACHE是否已经开启
*
* @return
*/
public static boolean cacheIsOpen() {
if (keyExists(CACHE_ISOPEN_KEY)) {
return true;
} else {
return false;
}
}
//demo
/*
public ModelAndView publishMood(@ModelAttribute("form") UserInfo user, HttpServletRequest request) {
//TODO
Object<T> obj = MemoryUtil.get(key);
if (obj == null) {
Object<T> obj = service.find(Entity.class);
MemoryUtil.set(key, obj);
}
reutrn null;
}
*/
}