使用注意:
接口:ICache,定义顶级方法
接口:IMemcachedCache,继承 ICache,定义应用级方法。
类:MemcachedCache 实现 IMemcachedCache 接口,主要的几个方法:
// 设置数据,同时删除本地缓存和做cluster异步分发
public Object put(String key, Object value, Date expiry)
public Object put(String key, Object value, int TTL)
public Object put(String key, Object value)
//先从本地缓存中获取,获取不到再到memcached中获取,同时加入本地缓存,TTL:失效时间,带有此参数的操作都按上述流程走。
public Object get(String key, int localTTL)
// 不走本地缓存,直接从memcached主机获取,如果获取不到,尝试从集群主机中获取,基于性考虑,只从集群中其他某个主机再获取
//如果获取不到,就直接返回。
public Object get(String key)
spring集成:
<bean id="memcachedCacheManager" class="com.alisoft.xplatform.asf.cache.memcached.MemcachedCacheManager"
init-method="start" destroy-method="stop">
<property name="configFile" value="cache/memcached-detail.xml"/>
</bean>
<bean id="mainService"
class="cn.com.xxxx.service.impl.MainServiceImpl">
<property name="memcachedCacheManager" ref="memcachedCacheManager"/>
</bean>
类中获取Manager:
protected MemcachedCacheManager memcachedCacheManager;
public MemcachedCacheManager getMemcachedCacheManager() {
return memcachedCacheManager;
}
public void setMemcachedCacheManager(MemcachedCacheManager memcachedCacheManager) {
this.memcachedCacheManager = memcachedCacheManager;
}
获取Cache:
IMemcachedCache memcachedCache1=memcachedCacheManager.getCache("mclient1");
IMemcachedCache memcachedCache2=memcachedCacheManager.getCache("mclient2");
改进,支持tokyo存取:
第一步:
修改MemCachedClient类中的set方法:
private boolean set( String cmdname, String key, Object value, Date expiry, Integer hashCode, boolean asString )
先定义两个常量:
//flags length
private static final int F_NUM_TOVAL =1;
private static final int F_VAULE_DEFAULT =32768;
在// now write the data to the cache server位置加入如下内容:
// now write the data to the cache server
try {
//解决ttserver不保存flags的问题
byte headflag=15;
try{
headflag=(byte)(Math.log(flags)/Math.log(2));
}catch (Exception e){}
byte[] cval=new byte[val.length+F_NUM_TOVAL];
cval[0]=headflag;
System.arraycopy(val,0,cval,1,val.length);
//完成
String cmd = new StringBuilder().append(cmdname).append(" ")
.append(key).append(" ").append(flags).append(" ")
.append(expiry.getTime() / 1000).append(" ")
.append(val.length).append("/r/n").toString();
//String.format( "%s %s %d %d %d/r/n", cmdname, key, flags, (expiry.getTime() / 1000), val.length );
sock.write( cmd.getBytes() );
红色部分是新添加的,然后将此类上述代码下的val 变量全部替换成cval变量。
第二步:
修改类MemCachedClient中的public Object get( String key, Integer hashCode, boolean asString ) 方法。
// read obj into buffer
byte[] tmpBuf = sock.readBytes(length);
/**
* 修正,使得可获取tokyo的数据
*/
int flag=F_VAULE_DEFAULT;
try{
flag=(int)Math.pow(2,tmpBuf[0]);
}catch(Exception e){
log.error("memcached get(),flag get error!");
}
byte[] buf = new byte[length-1];
System.arraycopy(tmpBuf,1,buf,0,length-1);
/**
* 修正结束
*/
if ( (flag & F_COMPRESSED) == F_COMPRESSED ) {
红色部分是新添加的,如果添加后变量flag显示已经定义,请将前面的定义注释掉。
本文介绍了一种使用Spring框架集成Memcached缓存的方法,并详细说明了如何通过修改客户端代码来支持Tokyo柜存储。文章覆盖了MemcachedCacheManager配置、主要缓存操作方法以及对Tokyo柜的支持改进。
9459

被折叠的 条评论
为什么被折叠?



