2016-03-15 43 views
1

從實例A,我創建了一個q1IQueue)也添加了ItemListener它。現在從Instace B我需要檢查,是否有任何ItemListener添加到同一個隊列中。如果沒有,那麼需要添加。如何檢查是否有任何ItemListener被添加到Hazelcast IQueue

So programatically我們如何檢查ItemListener是否添加到IQueue

更新與用例

在我們的電子商務網站,我們是爲flashsale

When admin configure an item for flashsale usign:我們將創建隊列(IQueue)該項目的一個的ItemListener還綁定到它

item Queue role: - 當用戶購買該物品的數量時,我們將爲該隊列添加n個標誌。

ItemListener role: - 對於itemAdded,我們將比較可用庫存和隊列大小,如果隊列大小達到可用庫存,則使庫存項目脫銷。

goal :-應該有一個單一的ItemListener爲acrross應用節點particuler項目

回答

1

這聽起來我要保證只有一個監聽器被添加到隊列中。爲什麼不使用最老的成員(特權集羣成員)來註冊偵聽器?你需要任何一種簡單的負載均衡的?導入

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

請找到更新的用例 – HybrisFreelance

+0

你可以使用一個原子putIfAbsent對IMAP自己註冊爲隊列的所有人或使用具有的tryLock的ILOCK。在這兩種情況下,您都需要意識到如果「處理節點」死亡,則必須有人接管。 – noctarius

+0

是綁定在Hazelcast客戶端而不是服務器上的「ItemListener」?對我來說更容易,如果我找到一些解決方法來檢查偵聽器是否存在 – HybrisFreelance

相關問題