首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

Spring3.1 缓存cache配备

2012-06-30 
Spring3.1 缓存cache配置最近准备把spring3.1的缓存功能引入到系统中,正好做到数据字典(类似下拉菜单管理)

Spring3.1 缓存cache配置
最近准备把spring3.1的缓存功能引入到系统中,正好做到数据字典(类似下拉菜单管理)需要用到缓存技术,于是初步使用了一把。
步骤:
1.必须引入ehcache-core-2.5.0.jar,同时spring的jar包需要升级到3.1
2.applicationContext.xml配置文件中需要加入
xmlns:p="http://www.springframework.org/schema/p"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
  http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache.xsd"
3.applicationContext.xml配置
<!-- 缓存 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="cacheManager" p:cache-manager-ref="ehcache" />
<bean id="ehcache" p:config-location="classpath:/ehcache.xml" />
4.
以下是service字典模块service缓存代码

//value对应ehcache.xml中配置的缓存名称,key是缓存的唯一标示,按照参数加方法名//一般来说是唯一的@Cacheable(value="DICT_CACHE",key="#dictId + 'getSystemDictByDictId'")public SystemDict getSystemDictByDictId(String dictId){Search search = new Search().addFilterEqual("dictId", dictId);return systemDictDAO.searchUnique(search);}@Cacheable(value="DICT_CACHE",key="#parentDictId + 'getSystemDictByDictId'")public List<SystemDict> findSystemDictByParentDictId(String parentDictId){Search search = new Search().addFilterEqual("parentDictId", parentDictId);return systemDictDAO.search(search);}@Cacheable(value="DICT_CACHE",key="#parentDictId + #status + 'getSystemDictByDictId'")public List<SystemDict> findSystemDictByParentDictId(String parentDictId,Integer status){Search search = new Search().addFilterEqual("parentDictId", parentDictId);search.addFilterEqual("status", status);return systemDictDAO.search(search);}//清除所有缓存,如果简单的话实际上可以加上需要清除哪些缓存,有针对性,但是不太好//控制@CacheEvict(value="DICT_CACHE",allEntries=true)public void saveSystemDict(SystemDict systemDict){systemDictDAO.save(systemDict);}@CacheEvict(value="DICT_CACHE",allEntries=true)public void deleteSystemDict(String dictId){systemDictDAO.deleteSystemDict(dictId);}


4.ehcache.xml放到classpath根目录
<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"      monitoring="autodetect">        <diskStore path="java.io.tmpdir"/>        <defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="true"        maxElementsOnDisk="10000000"        diskPersistent="false"        diskExpiryThreadIntervalSeconds="120"        memoryStoreEvictionPolicy="LRU"        />     <cache     name="DICT_CACHE"     maxElementsInMemory="10000"        eternal="true"        overflowToDisk="true"        maxElementsOnDisk="10000000"        diskPersistent="false"        /> </ehcache>


参考自网上其他几个相关帖子以及spring3.1文档,以上配置在我的工程中是可以正确运行的,如果有什么问题,欢迎留言。

热点排行