viren
viren

Reputation: 1103

Programatically setting up Near Cache in hazelcast and Java Verify if Near cache is returning data from local cache

I have created a Hazelcast set up with one node running hazelcast instance. My client application is using client config to read the cache from Hazelcast instance. I want to implement Near cache in my client app to use it as local cache. Could you please provide me an example where i can see how it is used in java. My current code is this

Hazel cast cache node

public class HazelCastNode1 {

    public static void main(String[] args) {
        Config cfg = new Config();
        HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);
        Map<Integer, String> citiesMap = instance.getMap("Cities");

        for(int i = 0; i < 100000; i++){
            citiesMap.put(i, "Vienna"+i);
        }
        System.out.println("Map Size:" + citiesMap.size()); 
    }
}

Client Code

public class ReadClient {
    public static void main(String[] args) {
        ClientConfig clientConfig = new ClientConfig();
        HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
        IMap<Integer, String> cumap = client.getMap("Cities");
        System.out.println(cumap.size());
    }  
}

Could you please give me an example which I can fit in here for Near cache implementation.

Upvotes: 4

Views: 5516

Answers (2)

pveentjer
pveentjer

Reputation: 11307

I don't know if there is any logging if a near cache is being hit.

To read out the metrics:

yourmap.getLocalMapStats().getNearCacheStats().getHits()

Upvotes: 0

viren
viren

Reputation: 1103

Hi am able to figure it out this is the code

public class ReadClient {

    public static void main(String[] args) {

        ClientConfig clientConfig = new ClientConfig();

        NearCacheConfig ncc = clientConfig.getNearCacheConfig("Cities");
        if(ncc == null){
            ncc = new NearCacheConfig();
        }
        ncc.setCacheLocalEntries(true);
        ncc.setEvictionPolicy("LRU");
        ncc.setMaxSize(500000);
        ncc.setInvalidateOnChange(true); 
        Map<String, NearCacheConfig> nearCache =  new HashMap<String, NearCacheConfig>();
        nearCache.put("CitiesLocal", ncc);
        clientConfig.addNearCacheConfig("Cities", ncc);
          HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);

        IMap<Integer, String> cumap = client.getMap("Cities");

        System.out.println(cumap.size());
        for(int i = 0 ; i < 100; i++){
            cumap.get(1);
        }

        System.out.println(cumap.getLocalMapStats().getNearCacheStats().getHits());
        cumap = client.getMap("CitiesLocal");
        System.out.println(cumap.size());
    }

}

But I still have one issue how to verify that near cache is returning data and it is not a remote call every time.

Upvotes: 5

Related Questions