package com.test.util; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * ehcache 缓存工具类 * * cacheName在ehcache.xml中配置 */ public class EhcacheUtil { public static CacheManager manager = CacheManager.create(); public static Object get(String cacheName, Object key) { Cache cache = manager.getCache(cacheName); if (cache != null) { Element element = cache.get(key); if (element != null) { return element.getObjectValue(); } } return null; } public static void put(String cacheName, Object key, Object value) { Cache cache = manager.getCache(cacheName); if (cache != null) { cache.put(new Element(key, value)); } } public static boolean remove(String cacheName, Object key) { Cache cache = manager.getCache(cacheName); if (cache != null) { return cache.remove(key); } return false; } public static void main(String[] args) { String key = "key"; String value = "hello"; EhcacheUtil.put("mytest", key, value); System.out.println(EhcacheUtil.get("mytest", key)); } }
ehcache.xml配置
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="true" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <cache name="mytest" maxElementsInMemory="100000" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"> </cache> <cache name="userCache" maxElementsInMemory="50000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="300" overflowToDisk="false" memoryStoreEvictionPolicy="LRU" /> </ehcache>
时间: 2024-11-16 19:36:56