如何使用EhCache获取存储对象

时间:2014-07-07 18:08:31

标签: java ehcache

使用的代码很适合存储,但是当我尝试基于键获取对象时它会抛出NullPointer异常。请帮我找到问题。

XML配置:

<ehcache>
    <diskStore path="/Leo-Softwares/DataStore_ehCache" />
        <cache name="Profit"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />
</ehcache>

存储利润的代码:

    Profit profit = new Profit();
    profit.setId(1);
    profit.setAmt("1000");
    profit.setLastupdate(new Date());

    ProfitDetail detail1 = new ProfitDetail();
    detail1.setId(1);
    detail1.setMax("1100");
    detail1.setMin("100");

    ProfitDetail detail2 = new ProfitDetail();
    detail2.setId(2);
    detail2.setMax("1200");
    detail2.setMin("200");

    List<ProfitDetail> details = new ArrayList<>();
    details.add(detail1);
    details.add(detail2);

    profit.setDetails(details);

    CacheManager manager = CacheManager.newInstance("EhCacheTest/ehcache.xml");

    Cache profitCache = manager.getCache("Profit");

    Element element = new Element(profit.getId(), profit);
    profitCache.put(element);

    int elementsInMemory = profitCache.getSize();
    System.out.println("elementsInMemory:"+elementsInMemory);

获取引发NullPointer异常的代码:

    CacheManager manager = CacheManager.newInstance("EhCacheTest/ehcache.xml");

    Cache profitCache = manager.getCache("Profit");

    Element element = profitCache.get(1);
    profit = (Profit)element.getValue();
    System.out.println(profit.getAmt()+":@@@:"+profit.getDetails().size());

0 个答案:

没有答案