我不确定我是否误解ehcache或者我是否刚刚没有正确实现它,但是在将某些内容保存到缓存后,当我去检索它时,我有一个空缓存!
基本上我正在尝试使用ehcache来替换@Singleton的使用。我需要在应用程序中的一个位置,我可以存储在内存数据中,可以从应用程序中的多个位置访问和共享。
我目前的代码如下:
@Stateless
@LocalBean
@Startup
public class DevicePoll {
...
@Schedule(minute = "*/2", hour = "*")
protected void getStatus() {
// Get all the sites
List<Site> sites = siteDAO.findAllSites();
// Setup the cache manager
CacheManager manager = CacheManager.getInstance();
Cache cache = manager.getCache("DEVICE_STATUS_CACHE");
// For testing lets get an item that we know was placed
Element e = cache.get("201");
for (Site site : sites) {
// Obtain the devices
List<Device> devices = deviceUtil.getDeviceTree(site);
// Create a new element and place it in the cache
Element element = new Element(site.getId(), devices);
cache.put(element);
}
// Shutdown the cache manager
manager.shutdown();
}
...
}
我的ehcache.xml是:
<defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="DEVICE_STATUS_CACHE" maxEntriesLocalHeap="1000" eternal="true" memoryStoreEvictionPolicy="FIFO"/>
答案 0 :(得分:1)
CacheManager
是高地人,你必须只有一个。当你在方法中创建并销毁它时,没有任何东西被保存,你需要更像这样的东西:
public class DevicePoll {
// usually cache and cache manager are injected
private Cache cache;
public DevicePoll() {
final CacheManager manager = CacheManager.getInstance();
this.cache = manager.getCache("DEVICE_STATUS_CACHE");
}
@Schedule(minute = "*/2", hour = "*")
protected void getStatus() {
// Get all the sites
List<Site> sites = siteDAO.findAllSites();
// For testing lets get an item that we know was placed
Element e = cache.get("201");
for (Site site : sites) {
// Obtain the devices
List<Device> devices = deviceUtil.getDeviceTree(site);
// Create a new element and place it in the cache
Element element = new Element(site.getId(), devices);
cache.put(element);
}
}
// ...
}