配置中心nacos使用体验
舟率率 11/17/2023 配置中心
package com.example.person.bigdata.common.service;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.Builder;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* @Author apophis
* @File NacosService
* @Time 2023/10/11 11:51
* @Description 工程描述
*/
@Builder
public class NacosService {
private static final String SERVER_ADDR = "http://xxxxxx:8848";
private static final String USERNAME = "xxxx";
private static final String PASSWORD = "xxxx";
private String dataId;
private String group;
private String namespace;
public Map<String, String> getConfMap() throws NacosException, IOException {
Properties nacosProp = new Properties();
nacosProp.put(PropertyKeyConst.SERVER_ADDR, SERVER_ADDR);
nacosProp.put(PropertyKeyConst.USERNAME, USERNAME);
nacosProp.put(PropertyKeyConst.PASSWORD, PASSWORD);
// 如果是public,则不需要namespace参数
nacosProp.put(PropertyKeyConst.NAMESPACE, this.namespace);
ConfigService configService = NacosFactory.createConfigService(nacosProp);
String content = configService.getConfig(this.dataId, this.group, 5000);
Properties properties = new Properties();
properties.load(new StringReader(content));
Map<String, String> map = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
map.put(key, value);
}
return map;
}
}
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
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