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!";
}
}