Spring Cache与Tair结合
spring3.1.M1中的cache功能比较简便。可以与Tair结合,这样就不必每次缓存数据库结果集或者hsf结果的时候都写一段同样的代码。
spring3.1.M1中的cache主要使用两个注解标记。
@Cacheable:负责将方法的返回值加入到缓存中
@CacheEvict:负责清除缓存
@Cacheable 支持如下几个参数:
value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL
condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL
@CacheEvict 支持如下几个参数:
value:缓存位置名称,不能为空,同上
key:缓存的key,默认为空,同上
condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
allEntries:true表示清除value中的全部缓存,默认为false
例子:
/** * TODO 如果没有注释,那么,你懂的 * * @author : mulou.zzy * Date: 13-3-6 * Time: 下午3:51 */ @Component("dos") public class DoSomeThing { @Cacheable(value = "default", key="#a") public String doa(int a) { return (int)( Math.random()* 1000 )+ ""; } @Cacheable(value = "default",condition="#a > 50") public String dob(int a) { return (int)(Math.random()* 1000 )+ ""; } //清除掉全部缓存 @CacheEvict(value="default", key = "#a") public void delete(int a) { System.out.println("do delete when a = " + a); } }
实现结合Tair的Cache必须继承Spring的Cache接口
/** * 一个简单的Tair Cache * * @author : mulou.zzy * Date: 13-3-6 * Time: 下午3:31 */ public class TairCache<K extends Serializable, V extends Serializable> implements Cache { @Resource private MultiClusterTairManager tairManager; private int nameSpace; public void setNameSpace(int nameSpace) { this.nameSpace = nameSpace; } private String name = "default"; @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public MultiClusterTairManager getNativeCache() { return tairManager; } @Override public TairResult get(Object key) { Result<DataEntry> result = tairManager.get(nameSpace, (K) key); if (result != null && result.isSuccess() && result.getValue() != null) { TairResult<V> tr = new TairResult(); tr.put((V) result.getValue().getValue()); return tr; } return null; } @Override public void put(Object key, Object value) { if (key != null || value != null) { if(key instanceof TairKey){ TairKey tairKey = (TairKey)key; this.tairManager.put(nameSpace, tairKey.getKey(), (V) value, tairKey.getVersion(), tairKey.getTime()); } this.tairManager.put(nameSpace, (K) key, (V) value); } } @Override public void evict(Object key) { this.tairManager.delete(nameSpace, (K) key); } @Override public void clear() { System.out.println("not allow to clear"); } }
因为@Cacheable标记中没有设置缓存时间和version的地方,所以我封装了一个TairKey类,存储Key和Version、time
/** * TODO 如果没有注释,那么,你懂的 * * @author : mulou.zzy * Date: 13-3-8 * Time: 上午11:34 */ public class TairKey implements Serializable { Serializable key; int time = 0; int version = 0; public int getTime() { return time; } public int getVersion() { return version; } public void setTime(int time) { this.time = time; } public void setVersion(int version) { this.version = version; } public Serializable getKey() { return key; } public void setKey(Serializable key) { this.key = key; } }
TairResult