Hazelcast 简明教程

Hazelcast - Quick Guide

Hazelcast - Introduction

Distributed In-memory Data Grid

数据网格是分布式缓存的超集。分布式缓存通常仅用于存储和检索跨缓存服务器分布的键值对。然而,数据网格除了支持键值对存储之外,还支持其他功能,例如,

  1. 它支持其他数据结构,如锁、信号量、集合、列表和队列。

  2. 它提供了一种通过丰富的查询语言(例如 SQL)查询存储数据的途径。

  3. 它提供了一个分布式执行引擎,帮助并行操作数据。

Benefits of Hazelcast

  1. Support multiple data structures − Hazelcast 支持与 Map 配合使用多种数据结构。其中一些是锁、信号量、队列、列表等。

  2. Fast R/W access − 鉴于所有数据都在内存中,Hazelcast 提供了非常高速的数据读/写访问。

  3. High availability − Hazelcast 支持跨机器分发数据以及对备份的附加支持。这意味着数据不会存储在单台机器上。因此,即使机器宕机(在分布式环境中经常发生),数据也不会丢失。

  4. High Performance − Hazelcast 提供可用于在多台工作机器间分配工作负载/计算/查询的构造。这意味着计算/查询使用来自多台机器的资源,可极大地减少执行时间。

  5. Easy to use − Hazelcast 实现并扩展了许多 java.util.concurrent 构造,使其非常易于使用并与代码集成。在机器上开始使用 Hazelcast 的配置只需将 Hazelcast jar 添加到我们的类路径中。

Hazelcast vs Other Caches & Key-Value stores

将 Hazelcast 与其他缓存(如 Ehcache、Guava 和 Caffeine)进行比较可能不是很有用。这是因为与其他缓存不同,Hazelcast 是一个分布式缓存,也就是说,它将数据跨机器/JVM 分发。尽管 Hazelcast 也可以在单个 JVM 上很好地工作,但它在分布式环境中更有用。

同样,将其与 MongoDB 之类的数据库进行比较也没有多大用处。这是因为 Hazelcast 主要将数据存储在内存中(尽管它也支持写入磁盘)。因此,它提供了较高的 R/W 速度,但限制在于数据需要存储在内存中。

与其他数据存储不同,Hazelcast 还支持缓存/存储复杂数据类型并提供了查询它们的接口。

然而,可以与 Redis 进行比较,它也提供了类似的功能。

Hazelcast vs Redis

在功能方面,Redis 和 Hazelcast 非常相似。然而,以下几点是 Hazelcast 优于 Redis 的地方−

  1. Built for Distributed Environment from ground-up − 与最初作为单机缓存的 Redis 不同,Hazelcast 从一开始就为了分布式环境而构建。

  2. Simple cluster scale in/out − 对于 Hazelcast,维护添加或删除节点的集群非常简单,例如,添加节点只需使用所需配置启动节点即可。删除节点只需要简单关闭节点。Hazelcast 会自动处理数据的分区等。对 Redis 进行相同的设置并执行上述操作需要更多的预防措施和人工工作。

  3. Less resources needs to support failover − Redis 遵循主-从模式。为了故障转移,Redis 需要额外的资源来设置 Redis Sentinel 。这些 Sentinel 节点负责在原始主节点宕机时将从库提升为主库。在 Hazelcast 中,所有节点被视为平等,节点的故障由其他节点检测到。因此,节点宕机的案例被以相当透明的方式处理,而且不需要任何额外的监控服务器。

  4. Simple Distributed Compute − Hazelcast 及其 EntryProcessor 提供了一个简单的接口,用于将代码发送到数据用于并行处理。这减少了数据在网上的传输。Redis 也支持这一点,但实现这一点需要人们了解 Lua 脚本,这增加额外的学习曲线。

Hazelcast - Setup

Hazelcast 要求 Java 1.6 或更高版本。Hazelcast 还可以与 .NET、C++ 或其他基于 JVM 的语言(如 Scala 和 Clojure)一起使用。不过,对于本教程,我们将使用 Java 8。

在我们继续之前,以下是我们将用于本教程的项目设置。

hazelcast/
├── com.example.demo/
│ ├── SingleInstanceHazelcastExample.java
│ ├── MultiInstanceHazelcastExample.java
│ ├── Server.java
│ └── ....
├── pom.xml
├── target/
├── hazelcast.xml
├── hazelcast-multicast.xml
├── ...

现在,我们只需在 hazelcast 目录中创建包,即 com.example.demo。然后,直接 cd 到该目录。我们将在即将到来的部分中查看其他文件。

Installing Hazelcast

安装 Hazelcast 只需将 JAR 文件添加到您的构建文件。基于您使用 Maven 或 Gradle,POM 文件或 build.gradle。

如果您使用 Gradle,将以下内容添加到 build.gradle 文件中就足够了−

dependencies {
   compile "com.hazelcast:hazelcast:3.12.12”
}

POM for the tutorial

我们将在教程中使用以下 POM −

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>1.0.0</modelVersion>
   <groupId>com.example</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project for Hazelcast</description>

   <properties>
      <maven.compiler.source>1.8</maven.compiler.source>
      <maven.compiler.target>1.8</maven.compiler.target>
   </properties>

   <dependencies>
      <dependency>
         <groupId>com.hazelcast</groupId>
         <artifactId>hazelcast</artifactId>
         <version>3.12.12</version>
      </dependency>
   </dependencies>

   <!-- Below build plugin is not needed for Hazelcast, it is being used only to created a shaded JAR so that -->
   <!-- using the output i.e. the JAR becomes simple for testing snippets in the tutorial-->
   <build>
      <plugins>
         <plugin>
            <!-- Create a shaded JAR and specify the entry point class-->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.2.4</version>
            <executions>
               <execution>
                  <phase>package</phase>
                     <goals>
                     <goal>shade</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>

Hazelcast - First Application

Hazelcast 可以单独运行(单节点),也可以运行多个节点以形成一个集群。让我们先尝试启动一个实例。

Single Instance

Example

现在,让我们尝试创建和使用 Hazelcast 集群的一个实例。为此,我们将创建 SingleInstanceHazelcastExample.java 文件。

package com.example.demo;

import java.util.Map;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class SingleInstanceHazelcastExample {
   public static void main(String... args){
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      System.out.println(“Hello world”);

      // perform a graceful shutdown
      hazelcast.shutdown();
   }
}

现在,让我们编译代码并执行它−

mvn clean install
java -cp target/demo-0.0.1-SNAPSHOT.jar
com.example.demo.SingleInstanceHazelcastExample

Output

如果执行上述代码,输出将是−

Hello World

然而,更重要的是,你还会注意到 Hazelcast 的日志行,它表示 Hazelcast 已启动。由于我们只运行此代码一次,即单个 JVM,我们的集群中只会有一个成员。

Jan 30, 2021 10:26:51 AM com.hazelcast.config.XmlConfigLocator
INFO: Loading 'hazelcast-default.xml' from classpath.
Jan 30, 2021 10:26:51 AM com.hazelcast.instance.AddressPicker
INFO: [LOCAL] [dev] [3.12.12] Prefer IPv4 stack is true.
Jan 30, 2021 10:26:52 AM com.hazelcast.instance.AddressPicker
INFO: [LOCAL] [dev] [3.12.12] Picked [localhost]:5701, using socket
ServerSocket[addr=/0:0:0:0:0:0:0:0,localport=5701], bind any local is true
Jan 30, 2021 10:26:52 AM com.hazelcast.system
...

Members {size:1, ver:1} [
   Member [localhost]:5701 - 9b764311-9f74-40e5-8a0a-85193bce227b this
]

Jan 30, 2021 10:26:56 AM com.hazelcast.core.LifecycleService
INFO: [localhost]:5701 [dev] [3.12.12] [localhost]:5701 is STARTED
...

You will also notice log lines from Hazelcast at the end which signifies
Hazelcast was shutdown:
INFO: [localhost]:5701 [dev] [3.12.12] Hazelcast Shutdown is completed in 784 ms.
Jan 30, 2021 10:26:57 AM com.hazelcast.core.LifecycleService
INFO: [localhost]:5701 [dev] [3.12.12] [localhost]:5701 is SHUTDOWN

Cluster: Multi Instance

现在,让我们创建 MultiInstanceHazelcastExample.java 文件(如下所示),它将用于多实例集群。

package com.example.demo;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class MultiInstanceHazelcastExample {
   public static void main(String... args) throws InterruptedException{
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();

      //print the socket address of this member and also the size of the cluster
      System.out.println(String.format("[%s]: No. of hazelcast members: %s",
         hazelcast.getCluster().getLocalMember().getSocketAddress(),
         hazelcast.getCluster().getMembers().size()));

      // wait for the member to join
      Thread.sleep(30000);

      //perform a graceful shutdown
      hazelcast.shutdown();
   }
}

让我们在 two different shells 上执行以下命令−

java -cp .\target\demo-0.0.1-SNAPSHOT.jar
com.example.demo.MultiInstanceHazelcastExample

你将在 1st shell 上注意到已启动 Hazelcast 实例,并且已分配了一个成员。请注意输出的最后一行,其中显示 single member using port 5701

Jan 30, 2021 12:20:21 PM com.hazelcast.internal.cluster.ClusterService
INFO: [localhost]:5701 [dev] [3.12.12]
Members {size:1, ver:1} [
   Member [localhost]:5701 - b0d5607b-47ab-47a2-b0eb-6c17c031fc2f this
]
Jan 30, 2021 12:20:21 PM com.hazelcast.core.LifecycleService
INFO: [localhost]:5701 [dev] [3.12.12] [localhost]:5701 is STARTED
[/localhost:5701]: No. of hazelcast members: 1

你将在 2nd shell 上注意到 Hazelcast 实例已加入第一个实例。请注意输出的最后一行,其中显示现在有 two members using port 5702

INFO: [localhost]:5702 [dev] [3.12.12]
Members {size:2, ver:2} [
   Member [localhost]:5701 - b0d5607b-47ab-47a2-b0eb-6c17c031fc2f
   Member [localhost]:5702 - 037b5fd9-1a1e-46f2-ae59-14c7b9724ec6 this
]
Jan 30, 2021 12:20:46 PM com.hazelcast.core.LifecycleService
INFO: [localhost]:5702 [dev] [3.12.12] [localhost]:5702 is STARTED
[/localhost:5702]: No. of hazelcast members: 2

Hazelcast - Configuration

Hazelcast 支持基于编程的配置以及基于 XML 的配置。然而,由于易于使用,XML 配置在生产中被大量使用。但 XML 配置在内部使用基于编程的配置。

XML Configuration

hazelcast.xml 是需要放置这些配置的位置。以以下位置(按相同顺序)搜索该文件,并从第一个可用位置选择它−

  1. 通过系统属性将 XML 的位置传递给 JVM - Dhazelcast.config=/path/to/hazelcast.xml

  2. 当前工作目录中的 hazelcast.xml

  3. hazelcast.xml in the classpath

  4. Hazelcast 提供的默认 hazelcast.xml

一旦找到 XML,Hazelcast 将从 XML 文件加载所需的配置。

让我们通过一个例子来尝试一下。在当前目录中创建一个名为 hazelcast.xml 的 XML。

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <!-- name of the instance -->
   <instance-name>XML_Hazelcast_Instance</instance-name>
</hazelcast>

现在的 XML 只包含 Hazelcast XML 的模式位置,该模式位置用于验证。但更重要的是,它包含实例名称。

Example

现在创建 XMLConfigLoadExample.java 文件,其中包含以下内容。

package com.example.demo;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class XMLConfigLoadExample {
   public static void main(String... args) throws InterruptedException{
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();

      //specified the name written in the XML file
      System.out.println(String.format("Name of the instance: %s",hazelcast.getName()));

      //perform a graceful shutdown
      hazelcast.shutdown();
   }
}

使用以下命令执行上面的 Java 文件 -

java -Dhazelcast.config=hazelcast.xml -cp .\target\demo-0.0.1-SNAPSHOT.jar
com.example.demo.XMLConfigLoadExample

Output

上述命令的输出将是 -

Jan 30, 2021 1:21:41 PM com.hazelcast.config.XmlConfigLocator
INFO: Loading configuration hazelcast.xml from System property
'hazelcast.config'
Jan 30, 2021 1:21:41 PM com.hazelcast.config.XmlConfigLocator
INFO: Using configuration file at C:\Users\demo\eclipseworkspace\
hazelcast\hazelcast.xml
...
Members {size:1, ver:1} [
   Member [localhost]:5701 - 3d400aed-ddb9-4e59-9429-3ab7773e7e09 this
]
Name of cluster: XML_Hazelcast_Instance

正如您所看到的,Hazelcast 已经加载了配置并打印了配置中指定的名字(最后一行)。

XML 中可以指定许多配置选项。完整列表可以在以下位置找到 -

在我们继续学习本教程时,我们将看到其中一些配置。

Programmatic Configuration

如前所述,XML 配置最终通过编程配置来完成。因此,让我们针对我们在 XML 配置中看到的同一个示例尝试编程配置。为此,让我们创建一个 ProgramaticConfigLoadExample.java 文件,其中包含以下内容。

Example

package com.example.demo;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class ProgramaticConfigLoadExample {
   public static void main(String... args) throws InterruptedException {
      Config config = new Config();
      config.setInstanceName("Programtic_Hazelcast_Instance");

      // initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(config);

      // specified the name written in the XML file
      System.out.println(String.format("Name of the instance: %s", hazelcast.getName()));

      // perform a graceful shutdown
      hazelcast.shutdown();
   }
}

让我们在不传递任何 hazelcast.xml 文件的情况下执行代码 -

java -cp .\target\demo-0.0.1-SNAPSHOT.jar
com.example.demo.ProgramaticConfigLoadExample

Output

上述代码的输出为:

Name of the instance: Programtic_Hazelcast_Instance

Logging

为了避免依赖项,Hazelcast 默认使用基于 JDK 的日志记录。但它也支持通过 slf4j, log4j 进行日志记录。例如,如果我们想要通过 logback 设置使用 sl4j 的日志记录,我们可以更新 POM 以包含以下依赖项 -

<!-- contains both sl4j bindings and the logback core -->
<dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
   <version>1.2.3</version>
</dependency>

Example

定义一个配置 logback.xml 文件并将它添加到您的类路径,例如 src/main/resources。

<configuration>
   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
         <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
      </encoder>
   </appender>

   <root level="info">
      <appender-ref ref="STDOUT" />
   </root>

   <logger name="com.hazelcast" level="error">
      <appender-ref ref="STDOUT" />
   </logger>
</configuration>

现在,当我们执行以下命令时,我们注意到关于 Hazelcast 成员创建等的所有元信息都没有被打印出来。这是因为我们已经把 Hazelcast 的日志级别设置为 error,并要求 Hazelcast 使用 sl4j 日志记录器。

java  -Dhazelcast.logging.type=slf4j -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.SingleInstanceHazelcastExample

Output

John

Variables

写入 XML 配置文件的值可能因环境而异。例如,在生产环境中,与开发环境相比,您可能对连接 Hazelcast 集群使用不同的用户名/密码。除了维护独立的 XML 文件外,人们还可以在 XML 文件中编写变量,然后通过命令行或以编程方式将这些变量传递给 Hazelcast。下面是通过命令行选择实例名称的一个示例。

因此,以下是我们的 XML 文件,其中包含变量 ${varname}

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

   <instance-name>${instance_name}</instance-name>
</hazelcast>

Example

以下是我们将用来打印变量值的示例 Java 代码 -

package com.example.demo;

import java.util.Map;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class XMLConfigLoadWithVariable {
   public static void main(String... args) throws InterruptedException {
      // initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();

      // specified the name written in the XML file
      System.out.println(String.format("Name of the instance: %s", hazelcast.getName()));

      // perform a graceful shutdown
      hazelcast.shutdown();
   }
}

以下命令 -

java -Dhazelcast.config=others\hazelcast.xml -Dinstance_name=dev_cluster -cp
.\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.XMLConfigLoadWithVariable

Output

并且输出显示变量已被 Hazelcast 正确替换。

Name of the instance: dev_cluster

Hazelcast - Setting up multi node instances

鉴于 Hazelcast 是一个分布式的 IMDG,并且通常在多台计算机上设置,因此它需要访问内部/外部网络。最重要的用例是在集群内发现 Hazelcast 节点。

Hazelcast 需要以下端口 -

  1. 1 个用于接收其他 Hazelcast 节点/客户端 Ping/数据的信息输入端口

  2. n 个用于向集群的其他成员发送 Ping/数据的信息输出端口

此节点发现以几种方式发生 -

  1. Multicast

  2. TCP/IP

  3. Amazon EC2 auto discovery

其中,我们将了解多播和 TCP/IP

Multicast

默认情况下启用多播连接机制。 https://en.wikipedia.org/wiki/Multicast 是一种通信形式,其中消息会发送到组中的所有节点。这是 Hazelcast 用于发现集群中其他成员的方式。早前我们已了解到,所有示例均使用多播来发现成员。

Example

现在,让我们明确启用它。在 hazelcast-multicast.xml 中添加以下内容:

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

   <network>
      <join>
         <multicast enabled="true" />
      </join>
   </network>
</hazelcast>

然后,让我们执行以下内容 -

java -Dhazelcast.config=hazelcast-multicast.xml -cp .\target\demo-0.0.1-
SNAPSHOT.jar com.example.demo.XMLConfigLoadExample

Output

在输出中,我们注意到以下来自 Hazelcast 的行,这实际上表示使用多播连接器来发现成员。

Jan 30, 2021 5:26:15 PM com.hazelcast.instance.Node
INFO: [localhost]:5701 [dev] [3.12.12] Creating MulticastJoiner

默认情况下,多播接受来自多播组内所有计算机的通信。这可能是一个安全隐患,这就是为什么通常在内部部署中会对多播通信使用防火墙的原因。因此,多播虽然适合开发工作,但在生产中,最好使用基于 TCP/IP 的发现。

TCP/IP

由于陈述了多播的缺陷,因此 TCP/IP 成为首选的通信方式。在 TCP/IP 的情况下,一个成员只能连接到已知/列出的成员。

Example

我们让 TCP/IP 用于发现机制。在 hazelcast-tcp.xml 中添加以下内容:

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

   <network>
      <join>
         <multicast enabled="false" />
         <tcp-ip enabled="true">
            <members>localhost</members>
         </tcp-ip>
      </join>
   </network>
</hazelcast>

然后,我们来执行以下命令 -

java -Dhazelcast.config=hazelcast-tcp.xml -cp .\target\demo-0.0.1-SNAPSHOT.jar
com.example.demo.XMLConfigLoadExample

Output

output 如下 -

INFO: [localhost]:5701 [dev] [3.12.12] Creating TcpIpJoiner
Jan 30, 2021 8:09:29 PM
com.hazelcast.spi.impl.operationexecutor.impl.OperationExecutorImpl

上述输出显示 TCP/IP 连接器用于连接两个成员。

如果您在两个不同的 Shell 上执行以下命令 -

java '-Dhazelcast.config=hazelcast-tcp.xml' -cp .\target\demo-0.0.1-SNAPSHOT.jar
com.example.demo.MultiInstanceHazelcastExample

我们看到以下输出 -

Members {size:2, ver:2} [
   Member [localhost]:5701 - 62eedeae-2701-4df0-843c-7c3655e16b0f
   Member [localhost]:5702 - 859c1b46-06e6-495a-8565-7320f7738dd1 this
]

上述输出表示节点能够使用 TCP/IP 连接,且两者都使用本地主机作为 IP 地址。

请注意我们在 XML 配置文件中可以指定更多 IP 或机器名称(会通过 DNS 解析)。

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

   <network>
      <join>
         <multicast enabled="false" />
         <tcp-ip enabled="true">
            <members>machine1, machine2....</members>
         </tcp-ip>
      </join>
   </network>
</hazelcast>

Hazelcast - Data Structures

java.util.concurrent 包提供了诸如 AtomicLong、CountDownLatch、ConcurrentHashMap 这样的数据结构,当有多个线程对数据结构读/写数据时,这些数据结构非常有用。但是为了提供线程安全性,所有这些线程都应在单个 JVM/机器上。

分布式数据结构有两个主要好处:

  1. Better Performance − 如果多台机器可以访问数据,则它们都可以并行工作并在更短的时间内完成工作。

  2. Data Backup − 如果一台 JVM/机器宕机,我们还有其他持有数据的 JVM/机器。

Hazelcast 提供了一种跨 JVM/机器分配数据结构的方法。

Hazelcast - Client

Hazelcast 客户端是对 Hazelcast 成员的轻量级客户端。Hazelcast 成员负责存储数据和分区。它们在传统的客户端-服务器模型中充当服务器。

Hazelcast 客户端仅用于访问存储在集群的 Hazelcast 成员中的数据。它们不负责存储数据,也不承担存储数据的任何所有权。

这些客户端有自己的生命周期并且不会影响 Hazelcast 成员实例。

我们先创建并运行 Server.java。

import java.util.Map;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
public class Server {
   public static void main(String... args){
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      //create a simple map
      Map<String, String> vehicleOwners = hazelcast.getMap("vehicleOwnerMap");
      // add key-value to map
      vehicleOwners.put("John", "Honda-9235");
      // do not shutdown, let the server run
      //hazelcast.shutdown();
   }
}

现在,运行上述类。

java -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.Server

对于设置客户端,我们还需要添加客户端 jar。

<dependency>
   <groupId>com.hazelcast</groupId>
   <artifactId>hazelcast-client</artifactId>
   <version>3.12.12</version>
</dependency>

现在让我们创建 Client.java。请注意,类似于 Hazelcast 成员,客户端也可以通过编程方式或通过 XML 配置(即通过 -Dhazelcast.client.config 或 hazelcast-client.xml)进行配置。

Example

我们使用默认配置,这意味着我们的客户端将能够连接到本地实例。

import java.util.Map;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
public class Client {
   public static void main(String... args){
      //initialize hazelcast client
      HazelcastInstance hzClient = HazelcastClient.newHazelcastClient();
      //read from map
      Map<String, String> vehicleOwners = hzClient.getMap("vehicleOwnerMap");
      System.out.println(vehicleOwners.get("John"));
      System.out.println("Member of cluster: " +
      hzClient.getCluster().getMembers());
      // perform shutdown
      hzClient.getLifecycleService().shutdown();
   }
}

现在,运行上述类。

java -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.Client

Output

它将生成如下输出:

Honda-9235
Member of cluster: [Member [localhost]:5701 - a47ec375-3105-42cd-96c7-fc5eb382e1b0]

从输出中看到 -

  1. 该集群仅包含一个成员,它来自 Server.java。

  2. 客户端能够访问存储在服务器内的映射。

Load Balancing

Hazelcast 客户端支持使用各种算法进行负载均衡。负载均衡确保负载在成员之间共享,集群中的任何单个成员都不会过载。默认的负载均衡机制设置为循环。使用 config 中的 loadBalancer 标记可以更改此设置。

我们可以使用配置中的 load-balancer 标记指定负载均衡器的类型。下面是一个随意选择节点的策略的示例。

<hazelcast-client xmlns="http://www.hazelcast.com/schema/client-config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.hazelcast.com/schema/client-config
   http://www.hazelcast.com/schema/client-config/hazelcastclient-config-4.2.xsd">
      <load-balancer type="random"/>
</hazelcast-client>

Failover

在分布式环境中,成员可能任意失败。为了支持故障转移,建议提供多个成员的地址。如果客户端可以访问任何一个成员,那它就能访问到其他成员。addressList 参数可以在客户端配置中指定。

例如,如果我们使用以下配置 -

<hazelcast-client xmlns="http://www.hazelcast.com/schema/client-config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.hazelcast.com/schema/client-config
   http://www.hazelcast.com/schema/client-config/hazelcastclient-config-4.2.xsd">
   <address-list>machine1, machine2</address-list>
</hazelcast-client>

即使 machine1 宕机,客户端也可以使用 machine2 访问集群的其他成员。

Hazelcast - Serialization

Hazelcast 最好用于数据/查询分布在多台机器的环境中。在这些环境中,数据需要从我们的 Java 对象序列化为能够在网络上传输的字节数组。

Hazelcast 支持多种序列化类型。但是,让我们关注一些常用类型,即 Java 序列化和 Java Externalizable。

Java Serialization

Example

首先让我们了解一下 Java 序列化。假设我们定义了一个实现了 Serializable 接口的 Employee 类。

public class Employee implements Serializable{
   private static final long serialVersionUID = 1L;
   private String name;
   private String department;
   public Employee(String name, String department) {
      super();
      this.name = name;
      this.department = department;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getDepartment() {
      return department;
   }
   public void setDepartment(String department) {
      this.department = department;
   }
   @Override
   public String toString() {
      return "Employee [name=" + name + ", department=" + department + "]";
   }
}

现在让我们编写代码将 Employee 对象添加到 Hazelcast 映射中。

public class EmployeeExample {
   public static void main(String... args){
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      //create a set to track employees
      Map<Employee, String> employeeOwners=hazelcast.getMap("employeeVehicleMap");
      Employee emp1 = new Employee("John Smith", "Computer Science");
      // add employee to set
      System.out.println("Serializing key-value and add to map");
      employeeOwners.put(emp1, "Honda");
      // check if emp1 is present in the set
      System.out.println("Serializing key for searching and Deserializing
      value got out of map");
      System.out.println(employeeOwners.get(emp1));
      // perform a graceful shutdown
      hazelcast.shutdown();
   }
}

Output

它将生成如下输出:

Serializing key-value and add to map
Serializing key for searching and Deserializing value got out of map
Honda

在此,一个非常重要的方面是,只需通过实现 Serializable 接口,我们就可以让 Hazelcast 使用 Java 序列化。另外请注意,Hazelcast 会存储键和值序列化的数据,而不是将它们像 HashMap 一样存储在内存中。因此,Hazelcast 负责序列化和反序列化的繁重工作。

Example

但是,这里有一个陷阱。在上述情况下,如果员工的部门发生改变怎么办?这个人仍然是同一个人。

public class EmployeeExampleFailing {
   public static void main(String... args){
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      //create a set to track employees
      Map<Employee, String> employeeOwners=hazelcast.getMap("employeeVehicleMap");
      Employee emp1 = new Employee("John Smith", "Computer Science");
      // add employee to map
      System.out.println("Serializing key-value and add to map");
      employeeOwners.put(emp1, "Honda");
      Employee empDeptChange = new Employee("John Smith", "Electronics");
      // check if emp1 is present in the set
      System.out.println("Checking if employee with John Smith is present");
      System.out.println(employeeOwners.containsKey(empDeptChange));
      Employee empSameDept = new Employee("John Smith", "Computer Science");
      System.out.println("Checking if employee with John Smith is present");
      System.out.println(employeeOwners.containsKey(empSameDept));
      // perform a graceful shutdown
      hazelcast.shutdown();
   }
}

Output

它将生成如下输出:

Serializing key-value and add to map
Checking if employee with name John Smith is present
false
Checking if employee with name John Smith is present
true

这是因为 Hazelcast 在比较时并不会对键(即 Employee)进行反序列化。它直接比较序列化键的字节码。因此,所有属性的值都相同的对象会被视为相同对象。但如果这些属性的值发生了改变,例如上述场景中的部门,则这两个键会被视为唯一键。

Java Externalizable

如果在上述示例中,我们在对键进行序列化/反序列化时不关心部门的值怎么办。Hazelcast 也支持 Java Externalizable,它让我们可以控制用于序列化和反序列化的标签。

Example

让我们修改我们的 Employee 类 −

public class EmplyoeeExternalizable implements Externalizable {
   private static final long serialVersionUID = 1L;
   private String name;
   private String department;
   public EmplyoeeExternalizable(String name, String department) {
      super();
      this.name = name;
      this.department = department;
   }
   @Override
   public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
      System.out.println("Deserializaing....");
      this.name = in.readUTF();
   }
   @Override
   public void writeExternal(ObjectOutput out) throws IOException {
      System.out.println("Serializing....");
      out.writeUTF(name);
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getDepartment() {
      return department;
   }
   public void setDepartment(String department) {
      this.department = department;
   }
   @Override
   public String toString() {
      return "Employee [name=" + name + ", department=" + department + "]";
   }
}

因此,正如您从代码中看到的那样,我们添加了 readExternal/writeExternal 方法,它们负责序列化/反序列化。鉴于我们在序列化/反序列化时是对部门不感兴趣的,所以我们在 readExternal/writeExternal 方法中排除了部门。

Example

现在,如果我们执行以下代码 −

public class EmployeeExamplePassing {
   public static void main(String... args){
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      //create a set to track employees
      Map<EmplyoeeExternalizable, String> employeeOwners=hazelcast.getMap("employeeVehicleMap");
      EmplyoeeExternalizable emp1 = new EmplyoeeExternalizable("John Smith", "Computer Science");
      // add employee to map
      employeeOwners.put(emp1, "Honda");
      EmplyoeeExternalizable empDeptChange = new EmplyoeeExternalizable("John Smith", "Electronics");
      // check if emp1 is present in the set
      System.out.println("Checking if employee with John Smith is present");
      System.out.println(employeeOwners.containsKey(empDeptChange));
      EmplyoeeExternalizable empSameDept = new EmplyoeeExternalizable("John Smith", "Computer Science");
      System.out.println("Checking if employee with John Smith is present");
      System.out.println(employeeOwners.containsKey(empSameDept));
      // perform a graceful shutdown
      hazelcast.shutdown();
   }
}

Output

我们得到的输出是 −

Serializing....
Checking if employee with John Smith is present
Serializing....
true
Checking if employee with John Smith is present
Serializing....
true

正如输出所示,使用 Externalizable 接口,我们可以仅提供员工姓名的序列化数据给 Hazelcast。

另外请注意,Hazelcast 序列化我们的键两次 −

  1. 一次是在存储键时,

  2. 第二次是在地图中搜索给定键时。如前文所述,这是因为 Hazelcast 使用序列化的字节数组来比较键。

总体而言,与 Serializable 相比,使用 Externalizable 的优势更多,因为如果我们想要更多地控制要序列化的属性以及我们希望如何处理它们,它提供了更多控制权。

Hazelcast - Spring Integration

Hazelcast 支持一种简单的方法来与 Spring Boot 应用程序集成。让我们通过一个示例来理解这一点。

我们将创建一个简单的 API 应用程序,它为获取公司员工信息提供了一个 API。为此,我们将使用 Spring Boot 驱动的 RESTController 以及 Hazelcast 来缓存数据。

请注意,要在 Spring Boot 中集成 Hazelcast,我们需要两件事——

  1. 将 Hazelcast 作为依赖项添加到我们的项目中。

  2. 定义一个配置(静态或编程)并将其提供给 Hazelcast

让我们首先定义 POM。请注意,我们必须指定 Hazelcast JAR 以便在 Spring Boot 项目中使用它。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.example</groupId>
   <artifactId>hazelcast</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project to explain Hazelcast integration with Spring Boot</description>

   <properties>
      <maven.compiler.target>1.8</maven.compiler.target>
      <maven.compiler.source>1.8</maven.compiler.source>
   </properties>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.4.0</version>
   </parent>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-cache</artifactId>
      </dependency>
      <dependency>
         <groupId>com.hazelcast</groupId>
         <artifactId>hazelcast-all</artifactId>
         <version>4.0.2</version>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

另外,将 hazelcast.xml 添加到 src/main/resources 中——

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

   <instance-name>XML_Hazelcast_Instance</instance-name>
</hazelcast>

定义 Spring Boot 要使用的入口点文件。确保我们指定了 @EnableCaching

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class CompanyApplication {
   public static void main(String[] args) {
      SpringApplication.run(CompanyApplication.class, args);
   }
}

让我们定义我们的员工 POJO ——

package com.example.demo;
import java.io.Serializable;
public class Employee implements Serializable{
   private static final long serialVersionUID = 1L;
   private int empId;
   private String name;
   private String department;
   public Employee(Integer id, String name, String department) {
      super();
      this.empId = id;
      this.name = name;
      this.department = department;
   }
   public int getEmpId() {
      return empId;
   }
   public void setEmpId(int empId) {
      this.empId = empId;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getDepartment() {
      return department;
   }
   public void setDepartment(String department) {
      this.department = department;
   }
   @Override
   public String toString() {
      return "Employee [empId=" + empId + ", name=" + name + ", department=" + department + "]";
   }
}

最后,让我们定义一个基本的 REST 控制器来访问员工 ——

package com.example.demo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1/")
class CompanyApplicationController{
   @Cacheable(value = "employee")
   @GetMapping("employee/{id}")
   public Employee getSubscriber(@PathVariable("id") int id) throws
   InterruptedException {
      System.out.println("Finding employee information with id " + id + " ...");
      Thread.sleep(5000);
      return new Employee(id, "John Smith", "CS");
   }
}

现在让我们通过运行命令来执行上述应用程序——

mvn clean install
mvn spring-boot:run

你会注意到命令的输出将包含 Hazelcast 成员信息,这意味着 Hazelcast 实例会使用 hazelcast.xml 配置自动为我们配置。

Members {size:1, ver:1} [
   Member [localhost]:5701 - 91b3df1d-a226-428a-bb74-6eec0a6abb14 this
]

现在让我们通过 curl 执行或使用浏览器来访问 API ——

curl -X GET http://localhost:8080/v1/employee/5

API 的输出将是我们的员工样本。

{
   "empId": 5,
   "name": "John Smith",
   "department": "CS"
}

在服务器日志中(即运行 Spring Boot 应用程序的位置),我们看到以下行——

Finding employee information with id 5 ...

但是,请注意,访问信息需要大约 5 秒(因为我们添加了睡眠)。但如果我们再次调用 API,API 的输出将立即显示。这是因为我们指定了 @Cacheable 符号。我们第一次 API 调用的数据已使用 Hazelcast 作为后端缓存。

Hazelcast - Monitoring

Hazelcast 提供有多种方法来监视集群。我们将研究如何通过 REST API 和 JMX 来进行监视。让我们首先研究 REST API。

Monitoring Hazelcast via REST API

要通过 REST API 监视集群或成员状态,必须为成员启用基于 REST API 的通信。这可以通过配置以及以编程方式来完成。

让我们通过 hazelcast-monitoring.xml 中的 XML 配置启用基于 REST 的监视 −

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <instance-name>XML_Hazelcast_Instance</instance-name>

   <network>
      <rest-api enabled="true">
         <endpoint-group name="CLUSTER_READ" enabled="true" />
         <endpoint-group name="HEALTH_CHECK" enabled="true" />
      </rest-api>
   </network>
</hazelcast>

让我们创建一个在 Server.java 文件中无限期运行的 Hazelcast 实例 −

public class Server {
   public static void main(String... args){
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      // do not shutdown, let the server run
      //hazelcast.shutdown();
   }
}

现在让我们启动集群 −

java '-Dhazelcast.config=hazelcast-monitoring.xml' -cp .\target\demo-0.0.1-
SNAPSHOT.jar com.example.demo.Server

启动后,可以通过调用 API 来了解集群的健康状况,如下所示 −

http://localhost:5701/hazelcast/health

上述 API 调用的 output

Hazelcast::NodeState=ACTIVE
Hazelcast::ClusterState=ACTIVE
Hazelcast::ClusterSafe=TRUE
Hazelcast::MigrationQueueSize=0
Hazelcast::ClusterSize=1

这表明集群中有一个成员,它处于活动状态。

有关节点的更详细信息,例如,IP、端口、名称,可以使用 − 找到

http://localhost:5701/hazelcast/rest/cluster

上述 API 的输出 −

Members {size:1, ver:1} [
   Member [localhost]:5701 - e6afefcb-6b7c-48b3-9ccb-63b4f147d79d this
]
ConnectionCount: 1
AllConnectionCount: 2

JMX monitoring

Hazelcast 还支持对其中嵌入的数据结构进行 JMX 监控,例如,IMap、Iqueue 等。

要启用 JMX 监控,我们首先需要启用基于 JVM 的 JMX 代理。可以通过将“-Dcom.sun.management.jmxremote”传递给 JVM 来完成此操作。若要使用不同的端口或使用身份验证,我们分别可以使用 -Dcom.sun.management.jmxremote.port、- Dcom.sun.management.jmxremote.authenticate。

除此之外,我们必须为 Hazelcast MBeans 启用 JMX。让我们通过 hazelcast-monitoring.xml 中的 XML 配置启用基于 JMX 的监控 −

<hazelcast
   xsi:schemaLocation="http://www.hazelcast.com/schema/config
   http://www.hazelcast.com/schema/config/hazelcast-config-3.12.12.xsd"
   xmlns="http://www.hazelcast.com/schema/config"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <instance-name>XML_Hazelcast_Instance</instance-name>

   <properties>
      <property name="hazelcast.jmx">true</property>
   </properties>
</hazelcast>

让我们创建一个 Hazelcast 实例,该实例在 Server.java 文件中无限期运行,并添加一个映射 −

class Server {
   public static void main(String... args){
      //initialize hazelcast server/instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      //create a simple map
      Map<String, String> vehicleOwners = hazelcast.getMap("vehicleOwnerMap");
      // add key-value to map
      vehicleOwners.put("John", "Honda-9235");
      // do not shutdown, let the server run
      //hazelcast.shutdown();
   }
}

现在我们执行以下命令启用 JMX −

java '-Dcom.sun.management.jmxremote' '-Dhazelcast.config=others\hazelcastmonitoring.
xml' -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.Server

现在,JMX 端口可以通过 JMX 客户端(如 jConsole、VisualVM 等)进行连接。

以下是连接使用 jConsole 时获得的结果示例,并查看 VehicleMap 的属性。正如我们可以看到,映射的名称为 vehicleOwnerMap,映射的大小为 1。

jmx clients

Hazelcast - Map Reduce & Aggregations

MapReduce 是一种计算模型,在您有大量数据且需要多台机器(即分布式环境)计算数据时,该模型对数据处理非常有用。它涉及将数据映射为键值对,然后进行“缩减”,即对这些键进行分组并在值上执行操作。

鉴于 Hazelcast 是在考虑分布式环境的情况下设计的,因此它自然而然地实现了 Map-Reduce 框架。

让我们用一个例子看看该怎么做。

例如,让我们假设我们有关于汽车(品牌和车号)及其车主的数据。

Honda-9235, John
Hyundai-235, Alice
Honda-935, Bob
Mercedes-235, Janice
Honda-925, Catnis
Hyundai-1925, Jane

现在,我们必须找出每个品牌的汽车数量,即现代、本田等。

Example

让我们尝试使用 MapReduce 找出 −

package com.example.demo;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.core.IMap;
import com.hazelcast.mapreduce.Context;
import com.hazelcast.mapreduce.Job;
import com.hazelcast.mapreduce.JobTracker;
import com.hazelcast.mapreduce.KeyValueSource;
import com.hazelcast.mapreduce.Mapper;
import com.hazelcast.mapreduce.Reducer;
import com.hazelcast.mapreduce.ReducerFactory;

public class MapReduce {
   public static void main(String[] args) throws ExecutionException,
   InterruptedException {
      try {
         // create two Hazelcast instances
         HazelcastInstance hzMember = Hazelcast.newHazelcastInstance();
         Hazelcast.newHazelcastInstance();
         IMap<String, String> vehicleOwnerMap=hzMember.getMap("vehicleOwnerMap");
         vehicleOwnerMap.put("Honda-9235", "John");
         vehicleOwnerMap.putc"Hyundai-235", "Alice");
         vehicleOwnerMap.put("Honda-935", "Bob");
         vehicleOwnerMap.put("Mercedes-235", "Janice");
         vehicleOwnerMap.put("Honda-925", "Catnis");
         vehicleOwnerMap.put("Hyundai-1925", "Jane");
         KeyValueSource<String, String> kvs=KeyValueSource.fromMap(vehicleOwnerMap);
         JobTracker tracker = hzMember.getJobTracker("vehicleBrandJob");
         Job<String, String> job = tracker.newJob(kvs);
         ICompletableFuture<Map<String, Integer>> myMapReduceFuture =
            job.mapper(new BrandMapper())
            .reducer(new BrandReducerFactory()).submit();
         Map<String, Integer&g; result = myMapReduceFuture.get();
         System.out.println("Final output: " + result);
      } finally {
         Hazelcast.shutdownAll();
      }
   }
   private static class BrandMapper implements Mapper<String, String, String, Integer> {
      @Override
      public void map(String key, String value, Context<String, Integer>
      context) {
         context.emit(key.split("-", 0)[0], 1);
      }
   }
   private static class BrandReducerFactory implements ReducerFactory<String, Integer, Integer> {
      @Override
      public Reducer<Integer, Integer> newReducer(String key) {
         return new BrandReducer();
      }
   }
   private static class BrandReducer extends Reducer<Integer, Integer> {
      private AtomicInteger count = new AtomicInteger(0);
      @Override
      public void reduce(Integer value) {
         count.addAndGet(value);
      }
      @Override
      public Integer finalizeReduce() {
         return count.get();
      }
   }
}

让我们尝试理解此代码 −

  1. 我们创建 Hazelcast 成员。在该示例中,我们有一个成员,但可以有多个成员。

  2. 我们使用模拟数据创建地图,并由此创建键值存储。

  3. 我们创建 Map-Reduce 作业,并要求它将键值存储用作数据。

  4. 然后,我们将作业提交到集群并等待完成。

  5. 映射器创建一个键,即从原始键中提取品牌信息,将值设置为 1,然后以键值对 (K-V) 形式将该信息发送到归约器。

  6. 归约器简单地对值求和,按键(即品牌名称)对数据进行分组。

Output

代码的输出 −

Final output: {Mercedes=1, Hyundai=2, Honda=3}

Hazelcast - Collection Listener

Hazelcast 在给定集合(例如队列、集合、列表等)更新时支持添加监听器。典型事件包括添加条目和删除条目。

让我们通过一个示例了解如何实现集合监听器。因此,假设我们要实现一个监听器,以跟踪集合中元素的数量。

Example

因此,让我们首先实现生产者 −

public class SetTimedProducer{
   public static void main(String... args) throws IOException,
   InterruptedException {
      //initialize hazelcast instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      Thread.sleep(5000);
      // create a set
      ISet<String> hzFruits = hazelcast.getSet("fruits");
      hzFruits.add("Mango");
      Thread.sleep(2000);
      hzFruits.add("Apple");
      Thread.sleep(2000);
      hzFruits.add("Banana");
      System.exit(0);
   }
}

现在,让我们实现监听器 −

package com.example.demo;

import java.io.IOException;
import com.hazelcast.core.ISet;
import com.hazelcast.core.ItemEvent;
import com.hazelcast.core.ItemListener;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class SetListener{
   public static void main(String... args) throws IOException, InterruptedException {
      //initialize hazelcast instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      // create a set
      ISet<String> hzFruits = hazelcast.getSet("fruits");
      ItemListener<String> listener = new FruitListener<String>();
      hzFruits.addItemListener(listener, true);
      System.exit(0);
   }
   private static class FruitListener<String> implements ItemListener<String> {
      private int count = 0;
      @Override
      public void itemAdded(ItemEvent<String> item) {
         System.out.println("item added" + item);
         count ++;
         System.out.println("Total elements" + count);
      }
      @Override
      public void itemRemoved(ItemEvent<String> item) {
         count --;
      }
   }
}

我们将首先运行生产者 −

java -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.SetTimedProducer

然后,我们运行监听器并使其无限期运行 −

java -cp .\target\demo-0.0.1-SNAPSHOT.jar com.example.demo.SetListener

Output

监听器的 output 如下所示 −

item added: ItemEvent{
   event=ADDED, item=Mango, member=Member [localhost]:5701-c28a60b7-3259-44bf-8793-54063d244394 this}
Total elements: 1

item added: ItemEvent{
   event=ADDED, item=Apple, member=Member [localhost]:5701-c28a60b7-3259-44bf-8793-54063d244394 this}
Total elements: 2

item added: ItemEvent{
   event=ADDED, item=Banana, member=Member [localhost]:5701-c28a60b7-3259-44bf-8793-54063d244394 this}
Total elements: 3

hzFruits.addItemListener(listener, true) 的调用告诉 Hazelcast 提供成员信息。如果设置为 false,则我们只会被通知条目已添加/删除。这有助于避免对条目进行序列化和反序列化以使其可用于监听器。

Hazelcast - Common Pitfalls & Performance Tips

Hazelcast Queue on single machine

Hazelcast 队列存储在单个成员上(以及不同机器上的备份)。这实际上意味着队列可以容纳一台机器可以容纳的任意多项。因此,队列容量不会通过添加更多成员而扩展。向队列中加载机器可以处理的数据量之外的数据会导致机器崩溃。

Using Map’s set method instead of put

如果我们使用 IMap 的 put(key, newValue),Hazelcast 会返回旧值。这意味着,反序列化会花费额外的计算和时间。其中还包括从网络发送的更多数据。相反,如果我们对旧值不感兴趣,我们可以使用返回 void 的 set(key, value)。

让我们了解如何存储和注入对 Hazelcast 结构的引用。以下代码创建一个名为“stock”的地图,并在一个位置添加芒果,在另一个位置添加苹果。

//initialize hazelcast instance
HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();

// create a map
IMap<String, String> hzStockTemp = hazelcast.getMap("stock");
hzStock.put("Mango", "4");

IMap<String, String> hzStockTemp2 = hazelcast.getMap("stock");
hzStock.put("Apple", "3");

然而,这里的问题在于我们使用了 getMap(“stock”) 两次。虽然在单个节点环境中此调用看起来无害,但它在集群环境中会造成缓慢。函数调用 getMap() 涉及到与集群的其他成员之间的网络往返。

因此,建议我们将对映射的引用存储在本地,并在操作映射时使用引用。例如 −

// create a map
IMap<String, String> hzStock = hazelcast.getMap("stock");
hzStock.put("Mango", "4");
hzStock.put("Apple", "3");

Hazelcast uses serialized data for object comparison

正如我们在早期的示例中所看到的,非常重要的一点是,Hazelcast 在比较键时不使用反序列化对象。因此,它无法访问我们在 equals/hashCode 方法中编写的代码。根据 Hazelcast,如果两个 Java 对象的所有属性值相同,那么键是相等的。

Use monitoring

在大型分布式系统中,监视起着非常重要的作用。使用 REST API 和 JMX 进行监视对于采取主动措施而不是采取被动措施非常重要。

Homogeneous cluster

Hazelcast 假设所有机器是相等的,即所有机器具有相同的资源。但是,如果我们的集群包含一台功能较弱的机器,例如内存较少、CPU 功能较弱等,那么如果计算发生在那台机器上,可能会造成缓慢。最糟糕的是,较弱的机器可能会耗尽资源,从而导致级联故障。因此,Hazelcast 成员必须具有相等的资源能力。