0%

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

需求背景

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

实现方案

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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/karaf-4.2.16/examples/karaf-config-example