Tuesday, 28 June 2022

Ehcache: Store the cache data to disk

Ehcache support tiering model to allow storing increasing amounts of data on slower tiers.

 


Example

PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.with(CacheManagerBuilder.persistence(new File("/Users/Shared/ehcache")))
.withCache("myCache",
		CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
				ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
						.offheap(2, MemoryUnit.MB).disk(20, MemoryUnit.MB, true)))
.build(true);

 

Above snippet defines a cache

a.   With heap to store 100 entries

b.   Off heap of size 2MB

c.    Disk of size 20MB

 

Objects stored in the Heap are managed by Jvm and unused objects are cleared by garbage collection cycle. On the other hand, the off-heap store refers to objects that are managed by EHCache, but stored outside the heap. Since off-heap memory is also maintained in the in-memory, it is faster than disk but slower than the heap store.

 

Find the below working application.

 

StoreDataToDisk.java

package com.sample.app;

import java.io.File;

import org.ehcache.Cache;
import org.ehcache.PersistentCacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;

public class StoreDataToDisk {

	public static void main(String[] args) {
		PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
				.with(CacheManagerBuilder.persistence(new File("/Users/Shared/ehcache")))
				.withCache("myCache",
						CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
								ResourcePoolsBuilder.newResourcePoolsBuilder().heap(100, EntryUnit.ENTRIES)
										.offheap(2, MemoryUnit.MB).disk(20, MemoryUnit.MB, true)))
				.build(true);

		Cache<Long, String> myCache = persistentCacheManager.getCache("myCache", Long.class, String.class);

		for (long i = 1; i < 100000; i++) {
			myCache.put(i, "data -> " + i);
		}

		persistentCacheManager.close();
	}

}

  Run the application, open the directory /Users/Shared/ehcache, you will see below data.

 

$tree /Users/Shared/ehcache
| | |____ehcache
| | | |____file
| | | | |____myCache_5d66446584040b6bac0bd0e2ee4e268602375623
| | | | | |____offheap-disk-store
| | | | | | |____ehcache-disk-store.meta
| | | | | | |____ehcache-disk-store.index
| | | | | | |____ehcache-disk-store.data

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment