Bogdan Timofeev
Bogdan Timofeev

Reputation: 1092

Proper way to configure Hazelcast with Spring

I've got a hazelcast cluster, running on the three nodes, with the following config (using ansible and docker for deployment):

hazelcast_cluster_login: "login"
hazelcast_cluster_password: "password"
hazelcast_maps: <map name="my_map"><backup-count>1</backup-count>
<time-to-live-seconds>3600</time-to-live-seconds></map>

And the following Spring config

@Configuration
@EnableCaching
public class CacheConfig {

    @Autowired
    private HazelcastProperties properties;

    @Bean
    public HazelcastInstance getConfig() {
        log.info("Connecting to Hazelcast on {} with login = {}",
            properties.getHosts(),
            properties.getLogin());

        ClientConfig clientConfig = new ClientConfig();
        clientConfig.getGroupConfig()
            .setName(properties.getLogin())
            .setPassword(properties.getPassword());
        clientConfig.getNetworkConfig()
            .setAddresses(properties.getHosts())
            .setConnectionAttemptLimit(0);
        HazelcastInstance instance = HazelcastClient.newHazelcastClient(clientConfig);
        return instance;
    }

    @Bean
    public CacheManager hazelcastCacheManager(HazelcastInstance 
        hazelcastInstance) {
        return new HazelcastCacheManager(hazelcastInstance);
    }

}

This code is able to successfully connect and authorize.

What is the proper way to use my_map Map in my application with @Cacheable? Is using @Cacheable("my_map") correct (couldn't find a way to diagnose it this map is empty or not) ? P.S. Tried to configure with config.addMapConfig(...), but this is not working with the running cluster.

Upvotes: 0

Views: 990

Answers (1)

Neil Stevenson
Neil Stevenson

Reputation: 3150

Try something like

@Service
public class MyService {

    @Cacheable("my_map")
    public Integer count(String input) {
        System.out.printf("input==%s%n", input);
        return input.length();
    }

}

This will create a IMap named "my_map" with a String key and an Integer value. So it caches the length of the string to save recalculating -- hardly worthwhile, more just a demonstration of the concept.

Call this a few times with the same input, the first call should trigger the method and you'll see the system output. The second call with the same input should use the cached value and the method won't be invoked, no system output.

You can access the underlying IMap directly using hazelcastInstance.getMap("my_map") and then do something like size() or keySet() on the map to see what's in it.

size() and keySet() are not operations you want to do normally. size() is computationally expensive, and keySet() may overflow the memory of the caller, since remote distributed maps can be huge.

Upvotes: 1

Related Questions