使用Hazelcast,如果成员关闭并打印消息,我如何创建事件或捕获?

时间:2017-09-20 08:04:42

标签: hazelcast

这是我的来源,如果某些成员由于某种原因被关闭,我怎么能打印消息呢?我想我可以举办一些活动或某种行动听众,但是如何......

import com.hazelcast.core.*; 
import com.hazelcast.config.*;

import java.util.Map;


/**  *  * @author alvel  */ public class ShutDown {
     public static void main(String[] args) {
        Config cfg = new Config();
        HazelcastInstance memberOne = Hazelcast.newHazelcastInstance(cfg);
         HazelcastInstance memberTwo = Hazelcast.newHazelcastInstance(cfg);
        Map<Integer, String> customerMap = memberOne.getMap("customers");
        customerMap.put(1, "google");
        customerMap.put(2, "apple");
        customerMap.put(3, "yahoo");
        customerMap.put(4, "microsoft");

        System.out.println("Hazelcast Nodes in this cluster"+Hazelcast.getAllHazelcastInstances().size());

        memberOne.shutdown();

         System.out.println("Hazelcast Nodes in this cluster After shutdown"+Hazelcast.getAllHazelcastInstances().size());

         Map<Integer, String> customerRestored = memberTwo.getMap("customers");
        for(String val:customerRestored.values()){
            System.out.println("-"+val);
        }

     } }

1 个答案:

答案 0 :(得分:1)

试试这个,它会在你的代码和新类中添加几行

public class ShutDown {

static {
    // ONLY TEMPORARY
    System.setProperty("hazelcast.logging.type", "none");
}

public static void main(String[] args) {
   Config cfg = new Config();
   HazelcastInstance memberOne = Hazelcast.newHazelcastInstance(cfg);
   //ADDED TO MEMBER ONE
   memberOne.getCluster().addMembershipListener(new ShutDownMembershipListener());
    HazelcastInstance memberTwo = Hazelcast.newHazelcastInstance(cfg);
   //ADDED TO MEMBER TWO
   memberTwo.getCluster().addMembershipListener(new ShutDownMembershipListener());
   Map<Integer, String> customerMap = memberOne.getMap("customers");
   customerMap.put(1, "google");
   customerMap.put(2, "apple");
   customerMap.put(3, "yahoo");
   customerMap.put(4, "microsoft");

   System.out.println("Hazelcast Nodes in this cluster"+Hazelcast.getAllHazelcastInstances().size());

   memberOne.shutdown();

    System.out.println("Hazelcast Nodes in this cluster After shutdown"+Hazelcast.getAllHazelcastInstances().size());

    Map<Integer, String> customerRestored = memberTwo.getMap("customers");
   for(String val:customerRestored.values()){
       System.out.println("-"+val);
   }

} 

static class ShutDownMembershipListener implements MembershipListener {

    @Override
    public void memberAdded(MembershipEvent membershipEvent) {
        System.out.println(this + membershipEvent.toString());
    }

    @Override
    public void memberAttributeChanged(MemberAttributeEvent arg0) {
    }

    @Override
    public void memberRemoved(MembershipEvent membershipEvent) {
        System.out.println(this + membershipEvent.toString());
    }
}
}

System.setProperty("hazelcast.logging.type", "none")仅用于测试,以便更简单地查看发生的情况。