java - 如何检查是否有 ItemListener 添加到 Hazelcast IQueue

标签 java caching hazelcast

从实例 A 中,我创建了一个 q1(IQueue),并向其中添加了 ItemListener。现在,我需要从实例 B 检查是否有任何 ItemListener 添加到同一队列中。如果没有则需要添加。

那么,我们如何以编程方式检查 ItemListener 是否已添加到 IQueue 中?

Updated with usecase

在我们的电子商务网站中,我们将其用于闪购

当管理员配置闪购商品时:我们将为该商品创建队列(IQueue),并为其绑定(bind)一个 ItemListener

元素队列角色:- 当用户购买 n 数量的该元素时,我们将向该队列添加 n 个标志。

ItemListener 角色:- 在 itemAdded 上,我们将比较可用库存和队列大小,如果队列大小达到可用库存,则使商品缺货。

目标:-跨应用程序节点的特定项目应该有一个ItemListener

最佳答案

在我看来,您只想保证只将一个监听器添加到队列中。为什么不使用最旧的成员(特权集群成员)来注册监听器?您需要任何类型的简单负载平衡吗?导入

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);
        }
    }
}

关于java - 如何检查是否有 ItemListener 添加到 Hazelcast IQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36013182/

相关文章:

java - JPA缓存未失效

java - 在 Unity 5 中使用 Hazelcast 客户端

java - 将 ImageView 高度设置为宽度的 50%

java - 如何解决自定义存储库 JPA 中的错误 "error in your SQL syntax"

java - JSF 和 xhtml 文件的自动重新加载

java - 设置 hazelcast 的配置属性

hazelcast - IMap Hazelcast 尺寸操作

java - 圆圈内的标签

java - Hazelcast 更新复制 map

c++ - 如何在 CONST 方法中访问类似于 GCC 的 sync_fetch_and_add 的 32 位或 64 位整数值?