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

com.zoi7.component.logback.zookeeper.LogbackRunner Maven / Gradle / Ivy

The newest version!
package com.zoi7.component.logback.zookeeper;

import com.zoi7.component.core.base.BaseClass;
import com.zoi7.component.zookeeper.ZkUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 *
 * 用于监听 logback 日志等级配置的动态修改
 * @author yjy
 * 2018-11-01 17:46
 */
@Component
public class LogbackRunner extends BaseClass implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(LogbackRunner.class);

    public static final String ZK_LOGBACK_ROOT = "/logbackLevel";

    @Autowired
    private ZkUtils zkUtils;
    private ZooKeeper zooKeeper;

    @Override
    public void run(String... args) throws IOException, KeeperException, InterruptedException {
        zooKeeper = zkUtils.getZooKeeper();
        // 检测根节点
        checkRoot();
        // 监听根节点变化
        zooKeeper.exists(ZK_LOGBACK_ROOT, new LevelWatcher(zooKeeper));
    }

    /**
     * 检查根节点是否存在, 如果不存在则创建
     * @throws KeeperException e
     * @throws InterruptedException e
     */
    private void checkRoot() throws KeeperException, InterruptedException {
        Stat stat = zooKeeper.exists(ZK_LOGBACK_ROOT, false);
        if (stat == null) {
            zooKeeper.create(ZK_LOGBACK_ROOT, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            log.info("[ZooKeeper] Create logback rootPath > node : {}", ZK_LOGBACK_ROOT);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy