Hazelcast 支持在给定集合(例如队列、集合、列表等)更新时添加侦听器。典型事件包括添加条目和删除条目。
让我们通过一个例子来看看如何实现一个集合监听器。所以,假设我们想要实现一个监听器来跟踪集合中元素的数量。
示例
那么,让我们首先实现生产者-
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
输出
来自监听器的 输出如下-
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,我们只会收到添加/删除条目的通知。这有助于避免需要序列化和反序列化条目以使其可供侦听器访问。