All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zoi7.component.zookeeper.ZkUtils Maven / Gradle / Ivy

package com.zoi7.component.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author yjy
 * 2018-10-23 11:42
 */
@Component
public class ZkUtils implements ApplicationContextAware {

    @Autowired
    private ZkConfig zkConfig;
    private static ApplicationContext context;
    private static volatile ZkUtils instance = null;

    public static ZkUtils getInstance() {
        if (instance == null) {
            synchronized (ZkUtils.class) {
                if (instance == null) {
                    instance = context.getBean(ZkUtils.class);
                }
            }
        }
        return instance;
    }

    public ZooKeeper getZooKeeper() throws IOException {
        return getZooKeeper(new DefaultWatcher());
    }

    public ZooKeeper getZooKeeper(Watcher watcher) throws IOException {
        return new ZooKeeper(zkConfig.getPath(), zkConfig.getSessionTimeout(), watcher);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ZkUtils.context = applicationContext;
    }

    /**
     * 默认watcher
     */
    private class DefaultWatcher implements Watcher {

        @Override
        public void process(WatchedEvent event) {
            // do nothing
        }
    }

    public ZkConfig getZkConfig() {
        return zkConfig;
    }

    public void setZkConfig(ZkConfig zkConfig) {
        this.zkConfig = zkConfig;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy