Hello World

安裝 hazelcast 並新增到 Java Build Path 後,你可以編寫啟動叢集工作的 Main.class

public static void main(String[] args){
    Config config = new Config();
    // creates a new HazelcastInstance (a new node in a cluster)
    HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
    // returns the Cluster that this HazelcastInstance is part of
    Cluster cluster = instance.getCluster();
    // get all devices, that are in the cluster
    Set<Member> setMembers = cluster.getMembers();

    // get ExecutorService that works on cluster instance
    ExecutorService mService = instance.getExecutorService("exec");
    
    for (int i = 0; i < setMembers.size(); i++) {
        // send a task for each member on service of HazelcastInstance
        final Future<String> future = mService.submit(new ClusterWorkingTask());
        
        String response = null;
        try {
            // wait for response
            response = future.get();
            System.out.println(response);  // each member return: Hello World!
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

建立可以在每個成員上執行的 ClusterWorkingTask.class

public class ClusterWorkingTask implements Callable<String>, Serializable {
    @Override
    public String call() throws Exception {
        // send Hello World! as result of execution
        return "Hello World!";
    }
}