Tony Borf
Tony Borf

Reputation: 4660

How do I use ehcache to reload data?

I have a list of 100 items (Strings) that I want to put in ehcache. I will set them to expire after 1 hour. After that I want to read the database and refresh the cache.

I have not been able to find an example on how to do this?

Does anyone know of one?

Thanks

Upvotes: 2

Views: 3699

Answers (2)

Alex
Alex

Reputation: 8313

Note, you can also use a SelfPopulatingCache in conjunction with cache element timeout to satisfy what you want.

Upvotes: 0

Ivan Sopov
Ivan Sopov

Reputation: 2370

Here is the method in CacheConfiguration to set live time of the element in cache http://ehcache.org/apidocs/net/sf/ehcache/config/CacheConfiguration.html#timeToLiveSeconds(long)

It has the corresponding argument in the constructor of cache http://ehcache.org/apidocs/net/sf/ehcache/Cache.html#Cache%28java.lang.String,%20int,%20boolean,%20boolean,%20long,%20long%29

These are default values for elements in particaluar cache - it can be specified for exact element too http://ehcache.org/apidocs/net/sf/ehcache/Element.html#setTimeToLive(int)

Here is the small example of using it:

import java.util.concurrent.TimeUnit;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhCacheFixedExpirationTest {
public static void main(String[] args) {
    CacheManager cacheManager = new CacheManager();
    Cache testCache = new Cache("testCache", 100, false, false, 10, 10);
    cacheManager.addCache(testCache);

    Element element = new Element("1", "20");
    element.setTimeToLive(1);
    testCache.put(element);

    long start = System.nanoTime();

    while (testCache.get("1") != null) {
        //wait
    }
    System.out.println(TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS));
}
}

Output is almost always 1000, so the precision is rather good. Is used Ehcache 2.4.6

Upvotes: 1

Related Questions