1

我不确定我是否误解了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"/>
4

1 回答 1

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);

        }
    }

    // ...
}
于 2013-09-27T15:46:20.527 回答