1.首先引入包
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.6</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.6</version> </dependency>
2.创建一个ehcache.xml文件,里面配置cache的信息,这个配置是包含了集群的配置:与192.168.93.129:40001的机器集群了:Ip为192.168.93.129机子的配置要将rmiUrls对应的数据改为这个配置文件的机子的IP地址,和对应的缓存名字
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=manual,rmiUrls=//192.168.93.129:40001/demoCache"/> <!--另一台机子的ip缓存信息--> <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="hostName=localhost,port=40001,socketTimeoutMillis=2000" /> <!--hostName代表本机子的ip--> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" maxElementsOnDisk="0" eternal="true" overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="0" diskSpoolBufferSizeMB="50" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LFU" > <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/> </defaultCache> <cache name="demoCache" maxElementsInMemory="100" maxElementsOnDisk="0" eternal="false" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="119" timeToLiveSeconds="119" diskSpoolBufferSizeMB="50" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="FIFO" > <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/> <!--监听这个cache--> </cache> </ehcache>
配置完后写代码:
放数据:
@RequestMapping("/testehcache.do") public void testehcache(HttpServletResponse response) throws IOException { URL url = getClass().getResource("ehcache.xml"); CacheManager singletonmanager = CacheManager.create(url); Cache cache = singletonmanager.getCache("demoCache"); //使用缓存 Element element = new Element("key1", "value1"); cache.put(element); cache.put(new Element("key2", "value2")); response.getWriter().println("我存放了数据"); }
拿数据:
@RequestMapping("/getcache.do") public void getcache(HttpServletResponse response) throws IOException { CacheManager singletonmanager = CacheManager.create(); Cache cache = singletonmanager.getCache("demoCache"); String one=cache.get("key1").getObjectValue().toString(); String two=cache.get("key2").getObjectValue().toString(); response.getWriter().println(one+two); }