配置中心
# 规则监听接口
public interface RulesChangeListener {
void onRulesChange(List<Rule> rules);/*Bootstap中实现*/
}
1
2
3
4
5
2
3
4
5
# 配置中心接口
public interface ConfigCenter {
void init(String serverAddr, String env);
void subscribeRulesChange(RulesChangeListener listener);
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 订阅规则变动
@Slf4j
public class NacosConfigCenter implements ConfigCenter {
private static final String DATA_ID = "api-gateway";/*在nacos自己配置*/
private String serverAddr;
private String env;
private ConfigService configService;
@Override
public void init(String serverAddr, String env) {
this.serverAddr = serverAddr;
this.env = env;
try {
configService = NacosFactory.createConfigService(serverAddr);
} catch (NacosException e) {
throw new RuntimeException(e);
}
}
@Override
public void subscribeRulesChange(RulesChangeListener listener) {
try {
String config = configService.getConfig(DATA_ID, env, 5000);
log.info("config from nacos: {}", config);
//{"rules":[{}, {}]}
List<Rule> rules = JSON.parseObject(config).getJSONArray("rules").toJavaList(Rule.class);
listener.onRulesChange(rules);
/*监听变化*/
configService.addListener(DATA_ID, env, new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
log.info("config from nacos: {}", configInfo);
List<Rule> rules = JSON.parseObject(configInfo).getJSONArray("rules").toJavaList(Rule.class);
listener.onRulesChange(rules);
}
});
} catch (NacosException e) {
throw new RuntimeException(e);
}
}
}
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
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