//MemcachedFactory.java
public classMemcachedFactory {//创建MemCachedClient全局对象
private static MemCachedClient memCachedClient = newMemCachedClient();static{//创建服务器列表及其权重
String[] servers = { "127.0.0.1:11211"};
Integer[] weights= { 3};//创建Socket连接池
SockIOPool pool =SockIOPool.getInstance();//设置服务器信息
pool.setServers(servers);
pool.setWeights(weights);
pool.setFailover(true);//设置初始连接数、最小和最大连接数以及最大处理时间
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.setAliveCheck(true);//初始化连接池
pool.initialize();
}protectedMemcachedFactory() {
}//Memcached 实例
protected static MemcachedFactory instance = newMemcachedFactory();public staticMemcachedFactory getInstance() {returninstance;
}/*** 添加缓存记录
*@paramkey
*@paramvalue
*@return
*/
public booleanadd(String key, Object value) {returnmemCachedClient.add(key, value);
}/*** 添加缓存记录,有效期为expiry
*@paramkey
*@paramvalue
*@paramexpiry
*@return
*/
public booleanadd(String key, Object value, Date expiry) {returnmemCachedClient.add(key, value, expiry);
}/*** 缓存查询结果对象QueryResult
*@paramkey
*@paramvalue
*@return
*/
public boolean add(String key, QueryResult
}/*** 提取缓存记录
*@paramkey
*@return
*/
publicObject get(String key) {returnmemCachedClient.get(key);
}/*** 判断缓存是否存在
*@paramkey
*@return
*/
public booleankeyExist(String key) {returnmemCachedClient.keyExists(key);
}
}
IndexController.java
@Controllerpublic classIndexCtroller{
@AutowiredprivateIIndexService indexService;
@RequestMapping(value= "/back/index")publicString index(HttpServletRequest request) {
MemcachedFactory mcInstance=MemcachedFactory.getInstance();
String jsonTree= null;//不存在key缓存记录则查询数据库并添加存入memcached
if(!mcInstance.keyExist("jsonTree")) {
List
List2JsonUtil
jsonTree= list2JsonUtil.getJosnStrFromList(menuList, null);
mcInstance.add("jsonTree", jsonTree);//否则直接从memcached中提取
}else{
jsonTree= (String) mcInstance.get("jsonTree");
}if(null !=jsonTree){
request.setAttribute("jsonTree", jsonTree);
}return "/back/index";
}
}