spring缓存 ehcache
ehcache 与spring集成实现简单的数据集缓存,事例是在ssh集成上实现,不对ssh做阐述。
1 : lib追加jar包
ehcache-1.2.4.jar
2 : applicationContext-service.xml
<bean id="GatewayIPManager" class="cn.com.superv.netmessage.oam.web.manager.GatewayIPManager"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> <property name="interProtocolDAO"> <ref bean="InterProtocolDAO" /> </property> <!-- 缓存对象--> <property name="gatewayIPCache" ref="GatewayIPManagerBean"/> </bean>
3 : applicationContext-cache.xml 缓存事例配置文件
<?xml version="1.0"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- 缓存管理 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="WEB-INF/ehcache.xml"> </property> </bean> <bean id="GatewayIPManagerBean" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager" ref="cacheManager"></property> <property name="cacheName" value="GatewayIPManager"></property> </bean> </beans>
4 : WEB-INF中添加ehcache.xml 缓冲对象属性配置
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <!-- maxElementsInMemory: 最大缓存100个对象 eternal:不是永久有效 overflowToDisk:缓存满了不写的磁盘 timeToIdleSeconds:180秒后没有读就失效 timeToLiveSeconds:300秒后失效 memoryStoreEvictionPolicy:当缓存数达到最大,将移除使用最少的缓存对象 --> <!-- 默认缓存设置 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="180" timeToLiveSeconds="300" overflowToDisk="true" memoryStoreEvictionPolicy="LRU" /> <!-- 缓存设置 --> <cache name="GatewayIPManager" maxElementsInMemory="100" eternal="false" overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LFU" /> </ehcache>
5 : GatewayIPManager class编写
private Cache gatewayIPCache ; public void setGatewayIPCache(Cache gatewayIPCache) { this.gatewayIPCache = gatewayIPCache; } private InterProtocolDAO interProtocolDAO ; public void setInterProtocolDAO(InterProtocolDAO interProtocolDAO) { this.interProtocolDAO = interProtocolDAO; } public boolean isExist(String wapip){ if (StringUtils.isEmpty(wapip)){ throw new NullPointerException("param 'wapid' can't be null ! "); } List<String> wapIPList = null ; //如果缓存对象不存在,去数据库中获取 Element element = gatewayIPCache.get(wapip); if (element == null) { wapIPList = interProtocolDAO.getInterProtocolsByType(InterProtocol.WAP_IP); element = new Element(wapip, wapIPList); gatewayIPCache.put(element); if (log.isInfoEnabled()) { log.info("----------数据列表加载到缓存中-------------"); } } wapIPList = (List<String>) element.getValue(); return wapIPList.contains(wapip); }