[TOC]
*****
# 1. 引入配置服務器的架構

# 2. 使用Nacos管理配置
```
第一步: 加依賴 compile('org.springframework.cloud:spring-cloud-starter-alibaba-nacos-config')
第二步: 寫配置 約定大于配置, 創建 bootstrap.yml, 添加配置
spring:
profiles:
active: dev
application:
name: ali-user-service
cloud:
nacos:
config:
server-addr: localhost:8848
namespace: 43dc7240-b605-44b9-8885-045fab030832
file-extension: yaml
```

```
@RestController
public class TestNacosConfigController {
@Value("${my.configuration}")
private String myConfiguration;
@GetMapping("/test-config")
public String testMyConfig() {
return myConfiguration;
}
}
```

# 3. 配置屬性動態刷新與回滾(附回滾Bug)
```
目標: 修改配置中心中的內容,不需要重啟服務 (@RefreshScope)
```
```
修改代碼:
@RestController
@RefreshScope
public class TestNacosConfigController {
@Value("${my.configuration}")
private String myConfiguration;
@GetMapping("/test-config")
public String testMyConfig() {
return myConfiguration;
}
}
```
```
回滾的bug(將會在1.2版本修復)
問題描述: 點擊歷史列表--回滾到初始狀態,配置列表中的配置數據會丟失,目前建議不要回滾到初始狀態
或者可以直接修改配置列表中的數據可以規避該問題
```

# 4. 應用的配置共享
```
ali-user-service-dev.yaml 指定專用配置;
ali-user-service.yaml 指通用配置,
專用配置優先級 大于 通用配置優先級
```

```
1. 多個微服務共享配置 -> 自動方式(根據[應用名-環境名].yaml方式)
spring:
profiles:
active: dev
application:
name: ali-user-service
cloud:
nacos:
config:
server-addr: localhost:8848
namespace: 43dc7240-b605-44b9-8885-045fab030832
file-extension: yaml
```
```
2. 多個微服務共享配置 -> shared-dataids 方式
# 配置管理
spring:
profiles:
active: dev
application:
name: ali-user-service
cloud:
nacos:
config:
server-addr: localhost:8848
namespace: 43dc7240-b605-44b9-8885-045fab030832
file-extension: yaml
# 共享配置的DataId, 多個使用,分隔
# 越靠后,優先級越高; common2.yaml > common1.yaml
# .yaml后綴不能少,只支持yaml/properties
shared-dataids: common1.yaml,common2.yaml
# 哪些共享配置支持動態刷新,多個使用,分隔
refreshable-dataids: common1.yaml
```
```
3. 多個微服務共享配置 -> ext-config 方式
spring:
profiles:
active: dev
application:
name: ali-user-service
cloud:
nacos:
config:
server-addr: localhost:8848
namespace: 43dc7240-b605-44b9-8885-045fab030832
file-extension: yaml
# 共享配置的DataId, 多個使用,分隔
# 越靠后,優先級越高; common2.yaml > common1.yaml
ext-config:
- data-id: common1.yaml
# common1.yaml所在的group
group: DEFAULT_GROUP
# 是否允許刷新, 默認false
refresh: true
- data-id: common2.yaml
group: DEFAULT_GROUP
refresh: true
```
```
總結: 三種方式的優先級 shared-dataids < ext-config < 自動
```
# 5. 引導上下文
```
1. bootstrap.yml 就是引導上下文的文件,使用連接nacos的,讀取外部配置;
2. 引導上下文是Application Context的父上下文,因此profiles和application屬性要放在bootstrap.yml中;
3. 默認遠程配置 [優先級 大于 本地配置優先級],即 bootstrap > application
可以通過下方屬性修改優先級,注意該配置需要放到遠程的nacos控制臺中的屬性位置才能生效
```

# 6. 數據持久化
```
1. nacos作為服務發現組件數據是存放在本地的 /nacos/naming 中;
2. nacos作為配置服務器
配置數據: 存放在 $NACOS_HOME/data/derby-data 中(derby是Apache內嵌數據庫);
快照: /nacos/config
```
# 7. 搭建生產可用的Nacos集群
```
用mysql代替derby
參考: http://www.imooc.com/article/288153
```