Monday, 27 June 2022

Ehcache: Get the Cache instance by alias name

CacheManager#getCache method retrieves the Cache object associated with the given alias, return null if no cache exists with this alias name.

 

Signature

<K, V> Cache<K, V> getCache(String alias, Class<K> keyType, Class<V> valueType);

 

Example

Cache<Long, String> empCache = cacheManager.getCache("empCache", Long.class, String.class);

 


Find the below working application.

 

GetCacheByName.java

 

package com.sample.app;

import java.util.*;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;

public class GetCacheByName {

	public static void main(String[] args) {
		CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);

		cacheManager.createCache("empCache", CacheConfigurationBuilder
				.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build());

		Cache<Long, String> empCache = cacheManager.getCache("empCache", Long.class, String.class);

		empCache.put(1L, "Krishna");
		empCache.put(2L, "Ram");

		Set<Long> empids = new HashSet<>();
		empids.add(1L);
		empids.add(2L);
		empids.add(3L);

		Map<Long, String> empsInfo = empCache.getAll(empids);

		for (Long key : empsInfo.keySet()) {
			System.out.println(key + " -> " + empsInfo.get(key));
		}

		cacheManager.close();

	}

}

 

Output

1 -> Krishna
2 -> Ram
3 -> null

 

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment