总结分享-Karaf框架实现自定义配置文件自动加载生效

总结分享-Karaf框架实现自定义配置文件自动加载生效

精选文章moguli202024-12-27 17:51:1917A+A-

需求背景

在业务稳定运行过程中,希望能通过修改临时配置文件控制业务的行为,要求实时生效。

实现方案

已知karaf框架下,/etc/xxx.cfg文件的配置都是支持实时修改和生效的,参考这种实现机制自定义一个cfg文件即可:

package com.xxx.xxx;

import org.osgi.framework.BundleContext;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.component.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Dictionary;

@Component(immediate = true, property = "service.pid=xxx") public class AutoConfig implements ManagedService {
    protected static final Logger LOG = LoggerFactory.getLogger("xxx");

    private static final String FLAG = "xxx.xxx.enabled";

    public static boolean flag = true;

    @Activate public void activate(BundleContext context) {
        LOG.info("AutoConfig activated.");
    }

    @Deactivate public void deactivate() {
        LOG.info("AutoConfig deactivated.");
    }

    @Override public void updated(Dictionary properties) {
        try {
            if (null == properties) {
                LOG.info("Configuration updated with null properties, use default.");
                return;
            }

            Object object = properties.get(FLAG);
            if (null == object) {
                LOG.info("Configuration updated with null properties, use default.");
                return;
            }

            String valueFromConfigFile = (String) object;
            if ("TRUE".equalsIgnoreCase(valueFromConfigFile)) {
                flag = true;
            } else if ("FALSE".equalsIgnoreCase(valueFromConfigFile)) {
                flag = false;
            } else {
                LOG.error("Invalid value {} from config file, use default true.", valueFromConfigFile);
                flag = true;
            }

            LOG.info("Configuration updated, flag={}", flag);
        } catch (Exception e) {
            LOG.error("Error updating configuration, use default true.", e);
        }
    }
} 

参考资料

https://github.com/apache/karaf/tree/master/examples/karaf-config-example

点击这里复制本文地址 以上内容由莫古技术网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

莫古技术网 © All Rights Reserved.  滇ICP备2024046894号-2