- 下载2.5.2
- 部署
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| # 解压
unzip nacos-server-2.5.2.zip
cd nacos
# 设置密码
vi conf/application.properties
## 配置用于服务端之间请求的身份识别信息 随机生成
nacos.core.auth.server.identity.key=
nacos.core.auth.server.identity.value=
## 生成32位字符转为base64
nacos.core.auth.plugin.nacos.token.secret.key=
nacos.core.auth.enabled=true
# 启动
sh bin/startup.sh -m standalone
# 查看日志
tail -f logs/startup.log
# 关闭
sh bin/shutdown.sh
|
- 控制台 nacos/
- 命名空间:项目
- 分组:环境
- dataId:配置文件名称
1
2
3
4
5
| <dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.12</version>
</dependency>
|
配置示例
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
| nacos:
config:
bootstrap:
enable: true
log:
enable: true
server-addr: xxx.xxx.xxx.xxx:8848
data-id: xxx.yml
group: dev
type: yaml
namespace: xxx
max-retry: 10
auto-refresh: true
config-retry-time: 2333
config-long-poll-timeout: 46000
enable-remote-sync-config: true
remote-first: true
username: nacos
password: xxx
ext-config:
- data-id: xxx.yml
namespace: xxx
group: dev
max-retry: 10
type: yaml
auto-refresh: true
config-retry-time: 2333
config-long-poll-timeout: 46000
enable-remote-sync-config: true
|
数据源配置
1
| @NacosPropertySource(dataId = "xxx.yml", autoRefreshed = true, type = ConfigType.YAML)
|
数据库监听
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
| @Component
@Slf4j
public class DruidPasswordNacosListener {
@Resource
private DruidDataSource druidDataSource;
@NacosConfigListener(
dataId = "xxx.yml",
groupId = "dev"
)
public void onConfigChange(String content) {
log.info("Nacos监听到数据库配置修改");
try {
Yaml yaml = new Yaml();
Map<String, Object> map = yaml.load(content);
if (map == null) {
return;
}
Map<String, Object> spring = (Map<String, Object>) map.get("spring");
if (spring == null) {
return;
}
Map<String, Object> datasource = (Map<String, Object>) spring.get("datasource");
if (datasource == null) {
return;
}
String newPassword = (String) datasource.get("password");
if (newPassword == null || newPassword.isEmpty()) {
return;
}
String oldPassword = druidDataSource.getPassword();
if (newPassword.equals(oldPassword)) {
return;
}
// 🔥 1. 设置新密码
druidDataSource.setPassword(newPassword);
// 🔥 2. 软驱逐旧连接(平滑)
//druidDataSource.restart();
log.info("✅ Druid 数据库密码已通过 Nacos YML 动态更新");
} catch (Exception e) {
log.error("Nacos更新数据库密码异常",e);
}
}
}
|
文章作者
lim
上次更新
2026-01-07
(589ac56)
许可协议
CC BY-NC-ND 4.0