parantap dansana
parantap dansana

Reputation: 11

Hazelcast cache implementation

My java application(not web) accesses the DB for data and I want to access the Hazelcast as a cache so that when I run my java application through main it checks if the data is present in the cache or not and then tries to access the DB. basically I want to store the map of the hazelcast instance somewhere in local. for example

HazelcastInstance hzInstance = Hazelcast.newHazelcastInstance();
map<Long, String> map = hazelcastInstance.getMap("data");
if(map.contains("key"))
{
 access cache
}
else
{
 access DB and insert into the cache
}

such that I get the map "data" and its content(the map should not be empty when I run my java app again) .

Upvotes: 0

Views: 824

Answers (1)

František Hartman
František Hartman

Reputation: 15086

You can use MapLoader interface to pre-load the data when your application starts. It also automatically handles loading the value for a key from the store when it's not present in the map, from the MapLoader documentation:

When you have MapLoader implemented, a map.get() triggers the load() method if the requested entry does not exist in memory. The MapLoader retrieves the requested entry, hands it to Hazelcast, which adds it to the in-memory map. This automatic loading is called read-through persistence.

and

Although read-through persistence will retrieve a requested map entry from the external data store, retrieving each individual entry as it is requested is inefficient. Instead, use the MapLoader.loadAllKeys() method to pre-populate your in-memory map. When used, each Hazelcast cluster member connects to the database to retrieve its owned portion of the map. This parallel processing is the fastest way to retrieve entries from the data store.

This is an open-source feature.

If you want Hazelcast to actually persist the data locally on a disk, e.g. when loading the key from the database is a very expensive operation or when you want to avoid transferring large amounts of data when a node restarts and re-joins a cluster, there is a feature called persistence. This is an enterprise feature.

Upvotes: 2

Related Questions