总结分享-Karaf框架实现自定义配置文件自动加载生效
需求背景
在业务稳定运行过程中,希望能通过修改临时配置文件控制业务的行为,要求实时生效。
实现方案
已知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