ehcache persist to disk issues

后端 未结 8 1752
你的背包
你的背包 2020-12-23 14:30

I want to do something with ehcache in Java that I think should be extremely simple, but I\'ve spent enough time frustrating myself with the docs...

  1. Write a

8条回答
  •  失恋的感觉
    2020-12-23 15:08

    I think you should remove the manager.cacheExists(..) test and simply create your cache using testCache = manager.getCache("test"); instead of using new Cache(..). Even if your cache is diskPersistent, it won't exist until you get it the first time. (At least that's what I think as I'm only using getCache(..) and it does exactly what you are looking for)

    Note:

    You could also add something like this to make sure the cache exists:

    Cache cache = manager.getCache(name);
    if (cache == null) {
        throw new NullPointerException(String.format("no cache with name %s defined, please configure it in %s", name, url));
    }
    

    Note 2:

    If your configuration file is called ehcache.xml, you shouldn't use CacheManager.create(url). Instead use the CacheManager singleton: I think I've confused using CacheManager.create(url) with and using new CacheManager(url). Still, you should use the singleton for ehcache.xml and new CacheManager(url) for anything else.

    // ehcache.xml - shared between different invocations
    CacheManager defaultManager = CacheManager.getInstance();
    // others - avoid calling twice with same argument
    CacheManager manager = CacheManager.create(url);
    

    Using CacheManager.create(..) is problematic as it might completely ignore the passed URL if any of the create(..) methods or getInstance() have been called before:

    public static CacheManager create(URL configurationFileURL) throws CacheException {
        synchronized (CacheManager.class) {
            if (singleton == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Creating new CacheManager with config URL: " + configurationFileURL);
                }
                singleton = new CacheManager(configurationFileURL);
    
            }
            return singleton;
        }
    }
    

    That's why I wouldn't recommend using any of the CacheManager.create(..) methods. Use CacheManager.getInstance() or new CacheManager(url).

提交回复
热议问题