hazelcast开始使用hazelcast


备注

本节概述了hazelcast是什么,以及开发人员可能想要使用它的原因。

它还应该提到hazelcast中的任何大型主题,并链接到相关主题。由于hazelcast的文档是新的,您可能需要创建这些相关主题的初始版本。

你好,世界!

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

安装或设置

Hazelcast在Java虚拟机(JVM)中运行。它与Java版本1.6.x,1.7.x和1.8.x兼容。安装和设置就像下载zip(或tar)存档,将未压缩的目录复制到所需的安装目录,以及将jar添加到Java类路径一样简单。

例如,从https://hazelcast.org/download/下载hazelcast zip后,在Linux上使用bash(在此示例中使用Hazelcast 3.7.4,但您下载的版本可能不同):

unzip hazelcast-3.7.4.zip
 

设置CLASSPATH变量:

export CLASSPATH=${CLASSPATH}:${PWD}:hazelcast-3.7.4/lib/hazelcast-3.7.4.jar
 

您现在应该能够通过执行启动脚本来启动hazelcast服务器来检查您的安装。在Linux上,执行start.sh脚本。示例脚本和预期输出:

$ hazelcast-3.7.4/bin/start.sh
JAVA_HOME environment variable not available.
Path to Java : /path/to/your/java

... ### More output here, ending with lines similar to: ### ...

Members [1] {
    Member [192.168.38.1]:5701 - 3456f96d-3646-459b-9199-caa6ebb3e5ee this
}

Jan 07, 2017 8:30:53 PM com.hazelcast.core.LifecycleService
INFO: [192.168.XX.XX]:5701 [dev] [3.7.4] [192.168.38.1]:5701 is STARTED
 

注意:如果您的Java安装不在标准位置,则可能还必须设置JAVA_HOME环境变量。

您现在应该设置为下载并运行代码示例(可从http://download.hazelcast.com/code-samples/hazelcast-code-samples-3.7.4.zip获得) ,或者开始编写您的代码示例拥有简单的Java Hazelcast客户端,可以连接到刚刚启动的Hazelcast服务器节点。