Monday 27 June 2022

Ehcache: Create a cache

CacheManager#createCache method create an instance of Cache.

 

Signature

<K, V> Cache<K, V> createCache(String alias, CacheConfiguration<K, V> config);
<K, V> Cache<K, V> createCache(String alias, Builder<? extends CacheConfiguration<K, V>> configBuilder)

Example

Cache<Long, String> myCache1 = cacheManager.createCache("myCache1", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build());

Above snippet create a cache with alias name ‘myCache1’, where key is of type Long and value is of type String, and can store maximum of 100 elements.

 


Find the below working application.

 

CreateCacheDemo.java

package com.sample.app;

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 CreateCacheDemo {

	public static void main(String[] args) {

		CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);

		Cache<Long, String> myCache1 = cacheManager.createCache("myCache1", CacheConfigurationBuilder
				.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build());

		myCache1.put(11L, "Ram,45,11");
		String value1 = myCache1.get(11L);

		System.out.println("value1 : " + value1);

		cacheManager.close();

	}

}

Output

value1 : Ram,45,11

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment