Spring AOP+ehCache简单缓存系统解决方案
转自:http://blog.csdn.net/liuzhenwen/archive/2009/03/12/3983952.aspx
需要使用Spring来实现一个Cache简单的解决方案,具体需求如下:使用任意一个现有开源Cache Framework,要求可以Cache系统中Service或则DAO层的get/find等方法返回结果,如果数据更新(使用Create /update/delete方法),则刷新cache中相应的内容。
根据需求,计划使用Spring AOP + ehCache来实现这个功能,采用ehCache原因之一是Spring提供了ehCache的支持,至于为何仅仅支持ehCache而不支持 osCache和JBossCache无从得知(Hibernate???),但毕竟Spring提供了支持,可以减少一部分工作量:)。二是后来实现了 OSCache和JBoss Cache的方式后,经过简单测试发现几个Cache在效率上没有太大的区别(不考虑集群),决定采用ehCahce。
AOP嘛,少不了拦截器,先创建一个实现了MethodInterceptor接口的拦截器,用来拦截Service/DAO的方法调用,拦截到方法后,搜索该方法的结果在cache中是否存在,如果存在,返回cache中的缓存结果,如果不存在,返回查询数据库的结果,并将结果缓存到cache 中。
MethodCacheInterceptor.java

?
hibernate缓存
1.在applicationContext.xml中引入
<bean id="sessionFactory" ref="dataSource"/><property name="configLocation" value="${hibernate.config.location}" /><property name="mappingLocations"><list><value>classpath:/com/mysougou/mtmibp/center/core/entity/*.hbm.xml</value><value>classpath:/com/mysougou/mtmibp/cms/cms/entity/*.hbm.xml</value><value>classpath:/com/mysougou/mtmibp/cms/article/entity/*.hbm.xml</value><value>classpath:/com/mysougou/mtmibp/cms/download/entity/*.hbm.xml</value><value>classpath:/com/mysougou/mtmibp/cms/auxiliary/entity/*.hbm.xml</value></list></property><property name="hibernateProperties"><!--hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect--><!--hibernate.dialect=org.hibernate.dialect.SQLServerDialect--><value>hibernate.dialect=org.hibernate.dialect.SQLServerDialecthibernate.show_sql=truehibernate.format_sql=falsehibernate.query.substitutions=true 1, false 0hibernate.jdbc.batch_size=20hibernate.cache.provider_class=org.hibernate.cache.EhCacheProviderhibernate.cache.provider_configuration_file_resource_path=/ehcache-hibernate.xml</value></property><property name="entityInterceptor"> <ref local="treeInterceptor"/></property></bean>ehcache-hibernate.xml
?
<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <diskStore path="java.io.tmpdir/mysougou2/hibernate"/><cacheManagerEventListenerFactory properties=""/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/><cache name="com.mysougou.mtmibp.core.entity.Website" maxElementsInMemory="100" eternal="true" overflowToDisk="true"/><cache name="com.mysougou.mtmibp.core.entity.Global" maxElementsInMemory="1" eternal="true" overflowToDisk="true"/><cache name="com.mysougou.mtmibp.core.entity.Function" maxElementsInMemory="3000" eternal="true" overflowToDisk="true"/><cache name="com.mysougou.mtmibp.core.entity.Function.child" maxElementsInMemory="3000" eternal="true" overflowToDisk="true"/></ehcache>
?