ZooKeeper for Java/Spring Config?

前端 未结 6 845
梦毁少年i
梦毁少年i 2021-01-30 23:36

Are there any well documented use cases of Apache ZooKeeper being used to distribute configuration of Java applications, and in particular Spring services?

Like many use

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 00:04

    After finding a suggestion to use a FactoryBean to populate a regular PropertyPlaceholderConfigurer I've built this:

    package fms;
    
    import org.apache.zookeeper.KeeperException;
    import org.apache.zookeeper.WatchedEvent;
    import org.apache.zookeeper.Watcher;
    import org.apache.zookeeper.ZooKeeper;
    import org.apache.zookeeper.data.Stat;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.config.AbstractFactoryBean;
    
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class ZkPropertiesFactoryBean extends AbstractFactoryBean implements Watcher {
        private Logger LOGGER = LoggerFactory.getLogger(ZkPropertiesFactoryBean.class);
        private String zkConnect;
        private String path;
        private int timeout = 1000;
    
        @Override protected Properties createInstance() throws Exception {
            long start = System.currentTimeMillis();
            Properties p = new Properties();
            p.load(new ByteArrayInputStream(loadFromZk()));
            double duration = (System.currentTimeMillis() - start)/1000d;
            LOGGER.info(String.format("Loaded %d properties from %s:%s in %2.3f sec", p.size(), zkConnect, path, duration));
            return p;
        }
    
        @Override public Class getObjectType() {
            return Properties.class;
        }
    
        private byte[] loadFromZk() throws IOException, KeeperException, InterruptedException {Stat stat = new Stat();
            ZooKeeper zk = new ZooKeeper(zkConnect, timeout, this);
            return zk.getData(path, false, stat);
        }
    
        @Override public void process(WatchedEvent event) {}
    
        public void setPath(String path) {this.path = path;}
    
        public void setZkConnect(String zkConnect) {this.zkConnect = zkConnect;}
    }
    

    In the spring-config.xml you create the beans as follows:

    
    
    

提交回复
热议问题