1.下載並安裝Terracotta
http://www.terracotta.org/
2.啟動Terracotta
bin/start-tc-server.bat 或 bin/start-tc-server.sh
3.代碼
Set值類:
package my.test.terracotta; import java.io.InputStream; import my.test.ehcache1.EHCacheTest; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class TestTerracottaSet { public TestTerracottaSet() { InputStream is = EHCacheTest.class.getResourceAsStream("/my/test/terracotta/ehcache.xml"); CacheManager cacheManager = new CacheManager(is); Cache cache = cacheManager.getCache("sampleTerracottaCache"); for (int i = 0; i < 1001; i++) { cache.put(new Element("key" + i, "value" + i)); } } public static void main(String[] args) throws Exception { new TestTerracottaSet(); } }
Get值類:
package my.test.terracotta; import java.io.InputStream; import my.test.ehcache1.EHCacheTest; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class TestTerracottaGet { public TestTerracottaGet() { InputStream is = EHCacheTest.class.getResourceAsStream("/my/test/terracotta/ehcache.xml"); CacheManager cacheManager = new CacheManager(is); Cache cache = cacheManager.getCache("sampleTerracottaCache"); for (int i = 0; i < 1001; i++) { Element elem = cache.get("key" + i); if (elem == null) { System.out.println("key" + i + " not found"); } else { System.out.println("key" + i + "=" + elem.getValue()); } } } public static void main(String[] args) throws Exception { new TestTerracottaGet(); } }
設定檔:修改官方範例設定檔,添加
<terracottaConfig url="localhost:9510"/>
<cache name="sampleTerracottaCache" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="1800" overflowToDisk="false"> <terracotta/> </cache>
這是利用Terracotta伺服器來進行緩衝同步
4.運行
(1)先運行TestTerracottaSet類
(2)再運行TestTerracottaGet類
(3)運行結果:
key0=value0
key1=value1
key2=value2
key3=value3
key4=value4
key5=value5
key6=value6
key7=value7
key8=value8
key9=value9
key10=value10
......
key1000=value1000
可以通過Terrocotta控制台查看緩衝情況,如圖: