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