Create a Failover Client

In this tutorial, you’ll update the code in a Java client to automatically connect to a secondary, failover cluster if it cannot connect to its original, primary cluster. You’ll also run a simple test to make sure that your configuration is correct and then adjust it to include exception handling.

Context

Failover is an important feature of systems that rely on near-constant availability. In Hazelcast, a failover client automatically redirects its traffic to a secondary cluster when the client cannot connect to the primary cluster.

Step 1. Set Up Clusters and Clients

Create two clusters in Hazelcast Cloud that you’ll use as your primary and secondary clusters and then download and connect sample Java clients to them.

  1. Create the Cloud Standard cluster that you’ll use as your primary cluster. When the cluster is ready to use, the Quick Connection Guide is displayed.

  2. Select the Java icon and follow the on-screen instructions to download, extract, and connect the preconfigured Java client to your primary cluster.

  3. Create the Cloud Standard cluster that you’ll use as your secondary cluster.

  4. Follow the instructions in the Quick Connection Guide to download, extract, and connect the preconfigured Java client to your secondary cluster.

You now have two running clusters, and you’ve checked that both Java clients can connect.

Step 2. Configure a Failover Client

To create a failover client, update the configuration and code of the Java client for your primary cluster.

Start by adding the keystore files from the Java client of your secondary cluster.

  1. Go to the directory where you extracted the Java client for your secondary cluster and then navigate to src/main/resources.

  2. Rename the client.keystore file to client2.keystore and rename the client.truststore file to client2.truststore to avoid overwriting the files in your primary cluster keystore.

  3. Copy both files over to the src/main/resources directory of your primary cluster.

Update the code in the Java client (ClientwithSsl.java) of your primary cluster to include a failover class and the connection details for your secondary cluster. You can find these connection details in the Java client of your secondary cluster.

  1. Go to the directory where you extracted the Java client for your primary cluster and then navigate to src/main/java/com/hazelcast/cloud/.

  2. Open the Java client (ClientwithSsl.java) and make the following updates. An example failover client is also available for download.

ClientwithSsl.java
package sample.com.hazelcast.clientfailover;

import java.util.Properties;
import java.util.Random;

import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.ClientFailoverConfig; (1)
import com.hazelcast.config.SSLConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastJsonValue;
import com.hazelcast.map.IMap;
import com.hazelcast.sql.SqlResult;
import com.hazelcast.sql.SqlRow;
import com.hazelcast.sql.SqlService;



public class ClientWithSsl {

    public static void main(String[] args) throws Exception {

        ClientFailoverConfig clientFailoverConfig = new ClientFailoverConfig(); (2)
        clientFailoverConfig.addClientConfig(getPrimaryClientConfig());
        clientFailoverConfig.addClientConfig(getSecondaryClientConfig());

        HazelcastInstance client = HazelcastClient.newHazelcastFailoverClient(clientFailoverConfig);

        System.out.println("Connection Successful!");

        nonStopMapExample(client); (3)

        client.shutdown();

        System.exit(0);

    }

    (4)
    private static ClientConfig getPrimaryClientConfig() throws Exception {
        ClassLoader classLoader = ClientWithSsl.class.getClassLoader();
        Properties props = new Properties();
        props.setProperty("javax.net.ssl.keyStore", classLoader.getResource("client.keystore").toURI().getPath());
        props.setProperty("javax.net.ssl.keyStorePassword", "YOUR_KEYSTORE_PASSWORD");
        props.setProperty("javax.net.ssl.trustStore",
            classLoader.getResource("client.truststore").toURI().getPath());
        props.setProperty("javax.net.ssl.trustStorePassword", "YOUR_KEYSTORE_PASSWORD");
        ClientConfig config = new ClientConfig();
        config.getNetworkConfig().setSSLConfig(new SSLConfig().setEnabled(true).setProperties(props));
        config.getNetworkConfig().getCloudConfig()
            .setDiscoveryToken("YOUR_DISCOVERY_TOKEN")
            .setEnabled(true);
        config.setClusterName("YOUR_CLUSTER_ID");
        config.getConnectionStrategyConfig()
            .getConnectionRetryConfig()
            .setClusterConnectTimeoutMillis(10000); (5)
        config.setProperty("hazelcast.client.cloud.url", "https://api.cloud.hazelcast.com");

        return config;
        }
    
    (6)
    private static ClientConfig getSecondaryClientConfig() throws Exception {
        ClassLoader classLoader = ClientWithSsl.class.getClassLoader();
       Properties props = new Properties();
        props.setProperty("javax.net.ssl.keyStore", classLoader.getResource("client2.keystore").toURI().getPath()); (7)
        props.setProperty("javax.net.ssl.keyStorePassword", "YOUR_KEYSTORE_PASSWORD");
        props.setProperty("javax.net.ssl.trustStore",
            classLoader.getResource("client2.truststore").toURI().getPath()); (7)
        props.setProperty("javax.net.ssl.trustStorePassword", "YOUR_KEYSTORE_PASSWORD");
        ClientConfig config = new ClientConfig();
        config.getNetworkConfig().setSSLConfig(new SSLConfig().setEnabled(true).setProperties(props));
        config.getNetworkConfig().getCloudConfig()
           .setDiscoveryToken("YOUR_DISCOVERY_TOKEN")
           .setEnabled(true);
        config.setClusterName("YOUR_CLUSTER_ID");
        config.getConnectionStrategyConfig().getConnectionRetryConfig().setClusterConnectTimeoutMillis(10000);
        return config;
        }

    /**
     * This example shows how to work with Hazelcast maps, where the map is
     * updated continuously.
     *
     * @param client - a {@link HazelcastInstance} client.
     */
    private static void nonStopMapExample(HazelcastInstance client) {
        System.out.println("Now the map named 'map' will be filled with random entries.");

        IMap<String, String> map = client.getMap("map");
        Random random = new Random();
        int iterationCounter = 0;
        while (true) {
            int randomKey = random.nextInt(100_000);
            map.put("key-" + randomKey, "value-" + randomKey); // Replaced by exception handling
            map.get("key-" + random.nextInt(100_000));
            if (++iterationCounter == 10) {
                iterationCounter = 0;
                System.out.println("Current map size: " + map.size());
            }
        }
    }
}
1 Add import for the ClientFailoverConfig class.
2 Create a ClientFailoverConfig object.
3 For testing purposes, uncomment the nonStopMapExample(client) method.
4 Create the config object for the primary cluster.
5 For testing purposes, set setClusterConnectTimeoutMillis to 10000 milliseconds or ten seconds. This reduces the timeout period before the failover client tries to connect to an alternative cluster.
6 Create the config object for the secondary cluster.
7 Provide the keystore files for the secondary cluster.

Step 3. Verify Failover

Check that your failover client automatically connects to the secondary cluster when your primary cluster is stopped.

  1. Make sure that both Cloud Standard clusters are running.

  2. Connect your failover client to the primary cluster in the same way as you did in Step 1.

  3. Stop your primary cluster. From the dashboard of your primary cluster, in Cluster Details, select Pause. In the console, you’ll see the following messages in order as the client disconnects from your primary cluster and reconnects to the secondary cluster:

    • CLIENT_DISCONNECTED

    • CLIENT_CONNECTED

    • CLIENT_CHANGED_CLUSTER

If you’re using the nonStopMapExample in the sample Java client, your client stops. This is expected because write operations are not retryable when a cluster is disconnected. The client has sent a put request to the cluster but has not received a response, and so the result of the request is unknown. To prevent the client from overwriting more recent write operations, this write operation is stopped and an exception is thrown.

Step 4. Exception Handling

Update the nonStopMapExample() function in your failover client to trap the exception that is thrown when the primary cluster disconnects.

  1. Add the following try-catch block to the while loop in the nonStopMapExample() function. This code replaces the original map.put() function.

    try {
        map.put("key-" + randomKey, "value-" + randomKey);
    } catch (Exception e) {
        // Captures exception from disconnected client
        e.printStackTrace();
    }
  2. Verify your code again. This time the client continues to write map entries after it connects to the secondary cluster.

Summary

In this tutorial, you learned how to do the following:

  • Collect all the resources that you need to create a failover client for a primary and secondary cluster.

  • Create a failover client based on the sample Java client.

  • Test failover.

  • Add exception handling for operations that are not retryable.

Learn More

Use these resources to continue learning: