Search code examples
hazelcast

Add new Hazelcast member after HazelcastInstance has been created


I'm trying to add a new member to my newly created HazelcastInstance (after it has been initialized) but I cannot find the API to do so. I don't want to use Multicast, so I disabled it, here's the code:

Config config = new Config();
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);

I tried adding the members to the config after initialization, but it doesn't seem to do anything:

instance.getConfig().getNetworkConfig().getJoin().getTcpIpConfig().addMember("192.168.1.5");

The code above works if I call it before the Hazelcast.newHazelcastInstance(config) method has been invoked, but this is not a solution for me, as I want to have a running instance and I don't know the IP (or range) of the new member that should be added later on.

I'm not sure if this is the correct way to approach this, so any help is appreciated.

Thanks!


Solution

  • You need to define the Network Config and you should be knowing the list of IP addresses between which the Cluster would be communicating.
    Otherwise, you can just start a cluster by running multiple Hazelcast instances in a single machine/localhost itself.
    Please note that if you want your multiple instances to join and form a cluster, all the instances should be sharing the same configuration, otherwise they will form their own cluster. So best thing is to define the configuration in hazelcast.xml. If you want programmatic way, then you can follow below example.

        Config config = new Config();
        NetworkConfig network = config.getNetworkConfig();
        network.getJoin().getMulticastConfig().setEnabled(false);
        network.getJoin().getTcpIpConfig().setEnabled(true);
        network.setPortAutoIncrement(true);
        network.setPort(33001);
        network.getJoin().getTcpIpConfig().addMember("127.0.0.1");
    
        HazelcastInstance hz1 = Hazelcast.newHazelcastInstance(config);
        HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(config);
    

    The above code would start two instances in localhost within same JVM.

    Jun 24, 2016 4:35:42 PM com.hazelcast.cluster.ClusterService
    INFO: [127.0.0.1]:33001 [dev] [3.5] 
    Members [2] {
        Member [127.0.0.1]:33001 this
        Member [127.0.0.1]:33002
    }
    Jun 24, 2016 4:35:44 PM com.hazelcast.core.LifecycleService
    INFO: [127.0.0.1]:33002 [dev] [3.5] Address[127.0.0.1]:33002 is STARTED
    

    Another way is to just remove the hz2 line and run the same config again in its own JVM. Both will join and form a cluster.