在项目中使用到Memcached主要的目的是,通过缓存数据库查询结果,减少数据库访问次数,从而提高动态、数据库驱动网站的速度、提高可扩展性。Memcached是一个高性能的分布式内存对象缓存系统,基于一个存储键/值对的hashmap。
实现你的cache类
import net.spy.memcached.MemcachedClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public final class Memcached implements Cache{
public Object get(String key) {
Object result = null;
try {
result = memcachedClient.get(key);
} catch (Exception e) {
log.error("Failed to get ‘" + key + "‘ from cache.", e);
}
return result;
}
public void put(String key, Object value) {
put(key, value, expiredTime);
}
public void put(String key, Object value, int expiredTime) {
try {
memcachedClient.set(key, expiredTime, value);
} catch (Exception e) {
log.error("Failed to put ‘" + key + "‘ into cache.", e);
}
}
public void remove(String key) {
try {
memcachedClient.delete(key);
} catch (Exception e) {
log.error("Failed to remove cache ‘" + key + "‘.", e);
}
}
public void setExpiredTime(int expiredTime) {
this.expiredTime = expiredTime;
}
public void setMemcachedClient(MemcachedClient memcachedClient) {
this.memcachedClient = memcachedClient;
}
private MemcachedClient memcachedClient;
private int expiredTime = 60 * 120;
private static final Log log = LogFactory.getLog(Memcached.class);
}
在applicationContext里配置cache相关类关系和属性
具体属性的作用可以参考官方说明:https://code.google.com/p/spymemcached/wiki/SpringIntegration
参考:http://blog.sina.com.cn/s/blog_60e4b3a90101c1po.html