#同时配置多台缓存服务器
memcached.cache.servers=192.138.11.165:11211,192.138.11.166:11211
#配置session的服务器
memcached.session.servers=192.138.11.168:11211,192.138.11.169:11211
2:在spring的配置文件中添加对memcache的支持
在spring的配置文件中添加,整合到spring中
3:封装了memcache的一些方法,方便操作
public interface Cache
{
public abstract void set(String s, Object obj, int i);
public abstract Object get(String s);
public abstract Map getMulti(List list);
public abstract Object[] getMulti(String as[]);
public abstract boolean exists(String s);
public abstract void delete(String s);
}
public class MemcachedCache
implements Cache
{
public MemcachedCache()
{
}
public void set(String key, Object value, int expiry)
{
if(StringUtils.isEmpty(key) || value == null)
{
return;
} else
{
memcachedClient.set(key, expiry * 60, value);
return;
}
}
public Object get(String key)
{
if(StringUtils.isEmpty(key))
return Boolean.valueOf(false);
Object o;
try
{
o = memcachedClient.get(key);
}
catch(OperationTimeoutException e)
{
o = memcachedClient.get(key);
}
return o;
}
public Map getMulti(List keys)
{
if(keys == null || keys.size() == 0)
{
return new HashMap(0);
} else
{
String strKeys[] = new String[keys.size()];
strKeys = (String[])keys.toArray(strKeys);
return memcachedClient.getBulk(strKeys);
}
}
public Object[] getMulti(String keys[])
{
if(keys == null || keys.length == 0)
{
return new Object[0];
} else
{
Map map = memcachedClient.getBulk(keys);
return map.values().toArray();
}
}
public void delete(String key)
{
if(StringUtils.isEmpty(key))
{
return;
} else
{
memcachedClient.delete(key);
return;
}
}
public boolean exists(String key)
{
if(StringUtils.isEmpty(key))
return false;
else
return memcachedClient.get(key) != null;
}
public void setMemcachedClient(MemcachedClient memcachedClient)
{
this.memcachedClient = memcachedClient;
}
private MemcachedClient memcachedClient;
}
4:在项目运用memcache
配置好memacache的环境了,就可以在项目中应用了
public class TestMemcacheService {
private MemcachedCache defaultCache;
private final static String KEY = "modul_methodname";
//需要spring注入上面配置好的bean的ID为defaultCache的bean
public void setDefaultCache(MemcachedCache defaultCache) {
this.defaultCache = defaultCache;
}
String sql = null;
//首先从缓存中取数据,如果缓存中没有,说明数据过期了,这时候可以去数据库查询新的数据,再添加到缓存中,
//这样可以很大程度上提高了后台响应时间。
if (null != defaultCache.get(KEY)) {
return (List
}
sql = "select * " + " from test order by match_date desc limit 50 ";
executeQuery(sql, 1);
....
defaultCache.set(KEY, list, 15);
return list;
}