从实例A开始,我创建了一个q1
(IQueue
)也添加了ItemListener
。现在从Instace B我需要检查,是否有任何ItemListener添加到同一队列。如果没有则需要添加。
以编程方式,我们如何检查ItemListener是否已添加到IQueue
?
更新了usecase
在我们的电子商务网站中,我们将其用于flashsale
When admin configure an item for flashsale
:我们将为该项创建队列(IQueue
)并将一个ItemListener绑定到它
item Queue role
: - 当用户购买n个数量的项目时,我们会在该队列中添加n个标志。
ItemListener role
: - 在itemAdded上,我们将比较可用的库存和队列大小,如果队列大小达到可用库存,则使物料缺货。
goal :-
应用程序节点上应该有一个ItemListener
个特定项目
答案 0 :(得分:1)
听起来我想保证只有一个侦听器被添加到队列中。为什么不使用最老的成员(特权集群成员)来注册监听器?您需要任何简单的负载平衡吗?import
import com.hazelcast.core.*;
import java.util.UUID;
public class OneListenerPerQueue {
public static void main(String[] args) {
// Create Hazelcast instance
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
// Add a basic distributed object listener
hz.addDistributedObjectListener(new QueueListener(hz));
// Create 100 unique queues
for (int i = 0; i < 100; i++) {
String uniqueQueue = UUID.randomUUID().toString();
hz.getQueue(uniqueQueue);
}
}
private static class QueueListener
implements DistributedObjectListener {
private final PartitionService partitionService;
private QueueListener(HazelcastInstance hz) {
this.partitionService = hz.getPartitionService();
}
public void distributedObjectCreated(DistributedObjectEvent distributedObjectEvent) {
// DistirbutedObject from the event
DistributedObject distObj = distributedObjectEvent.getDistributedObject();
// If queue ask PartitionService if the name is assigned to the local member
if (distObj instanceof IQueue) {
Partition partition = partitionService.getPartition(distObj.getName());
if (partition.getOwner().localMember()) {
// If local than add our ItemListener
((IQueue) distObj).addItemListener(new MyItemListener(), true);
}
}
}
public void distributedObjectDestroyed(DistributedObjectEvent distributedObjectEvent) {
}
}
private static class MyItemListener implements ItemListener<String> {
public void itemAdded(ItemEvent<String> itemEvent) {
System.out.println(itemEvent);
}
public void itemRemoved(ItemEvent<String> itemEvent) {
System.out.println(itemEvent);
}
}
}