Apache ZooKeeper

**The Apache ZooKeeper system for distributed coordination is a high-performance service for building distributed applications.**

Apache ZooKeeper

DownLoad

bin目录下运行 zkServer

 ERROR [main:QuorumPeerMain@86] - Invalid config, exiting abnormally
 org.apache.zookeeper.server.quorum.QuorumPeerConfig$ConfigException: Error processing        C:\my\software\zookeeper-3.5.2-alpha\bin\..\conf\zoo.cfg
        at org.apache.zookeeper.server.quorum.QuorumPeerConfig.parse(QuorumPeerConfig.java:137)
        at org.apache.zookeeper.server.quorum.QuorumPeerMain.initializeAndRun(QuorumPeerMain.java:110)
        at org.apache.zookeeper.server.quorum.QuorumPeerMain.main(QuorumPeerMain.java:79)

报找不到zoo.cfg 配置文件
rename /config/zoo_simple.cfg to zoo.cfg 再运行即可

bin目录下运行 zkCli

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
[zk: localhost:2181(CONNECTED) 0] ls /
[zookeeper]
[zk: localhost:2181(CONNECTED) 1]

使用java连接服务器

public class Master implements Watcher {
    static Logger logger = LoggerFactory.getLogger(Master.class);
    ZooKeeper zk;
    String hostPort;


    Random random = new Random();
    String serverId = Integer.toBinaryString(random.nextInt());
    static boolean isLeader = false;


    public Master(String hostPort) {
        this.hostPort = hostPort;
    }

    void startZk() throws IOException {
        zk = new ZooKeeper(hostPort, 15000, this);
    }

    public void process(WatchedEvent watchedEvent) {
        System.out.println(watchedEvent);
    }

    void stopZk() throws InterruptedException {
        zk.close();
    }

     boolean checkMaster() {
        while (true) {
            try {
                Stat stat = new Stat();
                byte data[] = zk.getData("/master", false, stat);
                isLeader = new String(data).equals(serverId);
                return true;
            } catch (KeeperException.NodeExistsException e) {
                return false;
            } catch (KeeperException.ConnectionLossException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    void runForMaster() throws InterruptedException {
        while (true) {
            try {
                zk.create("/master", serverId.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                isLeader = true;
                break;
            } catch (KeeperException.NodeExistsException e) {
                isLeader = false;
                break;
            } catch (KeeperException e) {
                System.out.println(e.getMessage());
            }

            if (checkMaster()) {
                break;
            }

        }

    }

     AsyncCallback.StringCallback masterCreateCallback = new AsyncCallback.StringCallback() {
        public void processResult(int rc, String path, Object ctx, String name) {
            switch (KeeperException.Code.get(rc)) {
            case CONNECTIONLOSS:
                checkMaster();
                return;
            case OK:
                isLeader = true;
                break;
            default:
                isLeader = false;
            }
            System.out.println("I'm " + (isLeader ? "" : "not " + "the leader"));

        }
    };

    void bootStrap() {
        createParent("/works", new byte[0]);
        createParent("/assign", new byte[0]);
        createParent("/tasks", new byte[0]);
        createParent("/status", new byte[0]);

    }

    void createParent(String path, byte[] bytes) {

        zk.create(path, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, createPatentCallBack, bytes);
    }

    AsyncCallback.StringCallback createPatentCallBack = new AsyncCallback.StringCallback() {
        public void processResult(int i, String path, Object o, String s1) {
            switch (KeeperException.Code.get(i)) {
                case CONNECTIONLOSS:
                    createParent(path, (byte[]) o);
                    break;
                case OK:
                    logger.info("parent created");
                    break;
                case NODEEXISTS:
                    logger.warn("Praent already exist "+path);
                    break;

                default:
                    logger.error("something error",KeeperException.create(KeeperException.Code.get(i),path));
            }
        }
    };


    public static void main(String[] args) throws Exception {
        Master master = new Master("xxx.xx.xx.xxx");
        master.startZk();
        master.runForMaster();
        if (isLeader) {
            System.out.println("I'm the leader");
            Thread.sleep(60000);
        } else {
            System.out.println("someone else is the leader");
        }

        master.bootStrap();

//      master.stopZk();

    }
public class Worker implements Watcher {

    private static Logger logger = LoggerFactory.getLogger(Worker.class);

    ZooKeeper zk;
    String hostPort;
    Random random = new Random();
    String serverId = Integer.toBinaryString(random.nextInt());

    Worker(String hostPort) {
        this.hostPort = hostPort;
    }

    void startZk() throws IOException {
        zk = new ZooKeeper(hostPort, 15000, this);
    }

    public void process(WatchedEvent watchedEvent) {
        System.out.println(watchedEvent);
    }

    void register() {
        zk.create("/works/worker-" + serverId, "Idle".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, createWorlkCallback, null);

    }

    AsyncCallback.StringCallback createWorlkCallback = new AsyncCallback.StringCallback() {
        public void processResult(int i, String path, Object ctx, String s1) {
            switch (KeeperException.Code.get(i)) {
                case CONNECTIONLOSS:
                    register();
                    logger.info("register");
                    break;
                case OK:
                    logger.info("parent created");
                    break;
                case NODEEXISTS:
                    logger.warn("Praent already exist "+path);
                    break;

                default:
                    logger.error("something error",KeeperException.create(KeeperException.Code.get(i),path));
            }
        }
    };


    public static void main(String[] args) throws IOException, InterruptedException {
        Worker worker = new Worker("xxx.xx.xx.xxx");
        worker.startZk();
        worker.register();

        Thread.sleep(60000l);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值