Wednesday, November 30, 2016

Putting and getting data to/from infinispan

Example shown below is applicable and tested working in JBoss EAP 6.x and JBoss AS 7.x

1. Inject the cache container with @resouce annotation.
    a) name, inject with the container name
    b) lookup, inject with the jndi name configured in the cache container.

code below is presented with method (a)
@Resource(name = "java:jboss/infinispan/container/CACHE-CONTAINER-NAME-IN-STANDALONE.XML")
private CacheContainer container;

make sure the cache container name exist in standalone.xml 
else there will be NullPointerException when getting the cache from the cache container.


2. in the same class, create a method to add or update value to the cache.
public void addOrUpdateCacheValue(String cacheName, String key, Object value) {
    // get the cache map with cacheName from the cache container 
    Cache<String, Object> cache = container.getCache(cacheName);
    // add or update the cache map
    cache.put(key, value);
}


3. retrieve the value from the cache 
public Object getCache(String cacheName, String key) {
    return container.getCache(cacheName).get(key);
}


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...