Spring 3.2.1.RELEASE MVC 基于注解ehcache.xml 配置方式
载的关联包里的ehcache-spring-annotations.jar之外, 还需要spring-context-support.jar, cblib-2.2.jar.
Spring 3.0.5 MVC 基于注解ehcache.xml 配置方式 http://www.blogjava.net/zzzlyr/articles/343234.html
spring 3.0.5 发布后,公司使用Spring MVC +Hibernate 3.5 做项目,其中用到了缓存机制,spring 3.0.5 中ehcache配置方法很简单,其中缓存机制很细颗粒化,可以具体到把每个方式的返回值做缓存,好了不说废话下面开始:
需要JAR包:
第一:spring 3.0.5 其中JAR;
第二:另外需要增量JAR包(cglib-2.2.jar,ehcache-spring-annotations-1.1.2.jar)注意版本;
其中applicationContext.xml 其中配置:
加到你的文件中去,上边是头信息自己可以比照下,没有的加进去;
在你的 src 目录下新建ehcache.xml内容如下:
其中里边详细配置自己可以去上网搜下;
这样基本上配置完成了:
DAO层缓存:例如下边这个方法的返回值需要缓存:
@Cacheable(cacheName=”departCache”) 加上这句话,其中cacheName 对应ehcache.xml 中的<cache name=”departCache”
这样这个方法返回值就可以被缓存起来的了,但是怎么样把缓存数据和数据库中的数据实现同步呢?
如果对这个PO做update ,save,delete 可以实现这样策略如下:
好了到此配置完毕,但是更加详细缓存配置策略需要研究(例如:当update数据时候,不全部清掉缓存,就可以达到与数据库同步效果)
[url]以下配置经本人完成测试通过(只限于本版本)。
http://luck332.iteye.com/blog/1001783[/url]
编写测试类
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.dzf.cache; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.googlecode.ehcache.annotations.Cacheable; import com.googlecode.ehcache.annotations.TriggersRemove; @Service @Transactional public class CacheService{ @Cacheable(cacheName = "testCache") public String getName(int i){ System.out.println("Processing testCache"); return "nihao:"+i; } @TriggersRemove(cacheName="testCache") public void flush(){ System.out.println("Processing testFlushing"); } } |
很容易就把cache给管理起来了。相当的方便。
碰到问题:当在Hibernate也使用缓存的时候
会出现Another unnamed CacheManager already exists in the same VM错误,又如何解决呢?
有必要在spring和hibernate都配置ehcache缓存么?
一个是针对数据库缓存,一个是针对业务数据缓存.
