使用SSM注解做缓存操作
之前自己写过一个通过注解和AOP来实现缓存的代码,最早的原型来自于在淘宝工作时的一个项目。当时这段代码写得比较差,之后重构时发现之前的功能实现有很大的局限。主要问题在于:
最近同事推荐了一个开源项目:Simple-Spring-Memcached(简称ssm),它也是一个通过Annatation与AOP来完成缓存数据操作的开源项目。仔细看了一下代码,基本上把我之前碰到的问题都解决了,而且MultiCache这一块的实现超出我的预期。该项目主要优点如下:
下面介绍一下其中各annotation的使用。ssm项目中的Annotation主要分成以下几类
各Annotation的详细说明
?
@ReadThroughSingleCache(namespace = "Alpha", expiration = 30) public String getDateString(@ParameterValueKeyProvider final String key) { final Date now = new Date(); try { Thread.sleep(1500); } catch (InterruptedException ex) { } return now.toString() + ":" + now.getTime(); }
?
@InvalidateSingleCache(namespace = "Charlie") public void updateRandomString(@ParameterValueKeyProvider final Long key) { // Nothing really to do here. } @InvalidateSingleCache(namespace = "Charlie") @ReturnValueKeyProvider public Long updateRandomStringAgain(final Long key) { return key; }
?
@UpdateSingleCache(namespace = "Alpha", expiration = 30) public void overrideDateString(final int trash, @ParameterValueKeyProvider final String key, @ParameterDataUpdateContent final String overrideData) { } @UpdateSingleCache(namespace = "Bravo", expiration = 300) @ReturnDataUpdateContent public String updateTimestampValue(@ParameterValueKeyProvider final Long key) { try { Thread.sleep(100); } catch (InterruptedException ex) { } final Long now = new Date().getTime(); final String result = now.toString() + "-U-" + key.toString(); return result; }
?
@ReadThroughAssignCache(assignedKey = "SomePhatKey", namespace = "Echo", expiration = 3000) public List<String> getAssignStrings() { try { Thread.sleep(500); } catch (InterruptedException ex) { } final List<String> results = new ArrayList<String>(); final long extra = System.currentTimeMillis() % 20; final String base = System.currentTimeMillis() + ""; for (int ix = 0; ix < 20 + extra; ix++) { results.add(ix + "-" + base); } return results; }
?
@InvalidateAssignCache(assignedKey = "SomePhatKey", namespace = "Echo") public void invalidateAssignStrings() { }
?
@UpdateAssignCache(assignedKey = "SomePhatKey", namespace = "Echo", expiration = 3000) public void updateAssignStrings(int bubpkus, @ParameterDataUpdateContent final List<String> newData) { }
http://www.colorfuldays.org/program/java/ssm_memcache/
?
1 楼 夜神月 2012-05-16 目前我在dao曾有如下的注解配置: