Support configure preference for single config

Add log info.
pull/2459/head
Freeman Lau 3 years ago
parent e02ef61969
commit 146fd38c47

@ -8,15 +8,37 @@
1. 启动一个 Nacos server
添加配置 `test.yml`
```yaml
configdata:
user:
name: freeman
```
2. 设置配置偏好 `spring.cloud.nacos.config.preference=remote`
添加配置 `test2.yml`
```yaml
dev:
age: 22
```
2. 设置配置偏好
设置默认配置偏好
```yaml
spring:
cloud:
nacos:
config:
preference: remote
```
指定配置test2.yml设置配置偏好
```yaml
spring:
config:
import:
- optional:nacos:test.yml
- optional:nacos:test2.yml?preference=local
```
3. 访问 `localhost`
应该能看到值为 `freeman`,因为优先使用了配置中心配置
修改配置为 `spring.cloud.nacos.config.preference=local` 那么值应该为 `aa`
3. 验证
访问 `localhost`,应该能看到值为 `freeman: 20`,因为 `name` 优先使用了配置中心配置,`age` 优先使用本地配置。

@ -8,15 +8,37 @@ This project demonstrates how to use config preferences.
1. Start a Nacos server
add configuration `test.yml`
```yaml
configdata:
user:
name: freeman
```
2. Set config preference `spring.cloud.nacos.config.preference=remote`
add configuration `test2.yml`
```yaml
dev:
age: 22
```
2. Set configuration preference
Set default configuration preference
```yaml
spring:
cloud:
nacos:
config:
preference: remote
```
Specify configuration (test 2.yml) to set configuration preference
```yaml
spring:
config:
import:
- optional:nacos:test.yml
- optional:nacos:test2.yml?preference=local
```
3. access `localhost`
You should see a value of `freeman`, because the configuration center configuration is used first.
Modify the configuration to `spring.cloud.nacos.config.preference=local` then the value should be `aa`.
3. Verify
Access `localhost`, you should see the value of `freeman: 20`, because `name` uses the configuration center configuration first, and `age` uses the local configuration first.

@ -19,6 +19,8 @@ package com.alibaba.cloud.configpreference.examples.controller;
import com.alibaba.cloud.configpreference.examples.model.UserProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@ -28,14 +30,17 @@ import org.springframework.web.bind.annotation.RestController;
* @author freeman
*/
@RestController
@RefreshScope
public class UserController {
@Autowired
private UserProperties userProperties;
@Value("${dev.age}")
private int age;
@GetMapping
public String getName() {
return userProperties.getName();
return userProperties.getName() + ": " + age;
}
}

@ -12,6 +12,7 @@ spring:
config:
import:
- optional:nacos:test.yml
- optional:nacos:test2.yml?preference=local
profiles:
active: dev
@ -22,4 +23,6 @@ spring:
on-profile: dev
configdata:
user:
name: bb
name: bb
dev:
age: 20

@ -88,12 +88,10 @@ public class NacosConfigDataLoader implements ConfigDataLoader<NacosConfigDataRe
NacosPropertySourceRepository.collectNacosPropertySource(propertySource);
return new ConfigData(propertySources, getOptions(context));
return new ConfigData(propertySources, getOptions(context, resource));
}
catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug("Error getting properties from nacos: " + resource, e);
}
log.warn("Error getting properties from nacos: " + resource, e);
if (!resource.isOptional()) {
throw new ConfigDataResourceNotFoundException(resource, e);
}
@ -101,15 +99,12 @@ public class NacosConfigDataLoader implements ConfigDataLoader<NacosConfigDataRe
return null;
}
private Option[] getOptions(ConfigDataLoaderContext context) {
Binder binder = context.getBootstrapContext().get(Binder.class);
ConfigPreference preference = binder
.bind("spring.cloud.nacos.config.preference", ConfigPreference.class)
.orElse(LOCAL);
private Option[] getOptions(ConfigDataLoaderContext context,
NacosConfigDataResource resource) {
List<Option> options = new ArrayList<>();
options.add(IGNORE_IMPORTS);
options.add(IGNORE_PROFILES);
if (preference == REMOTE) {
if (getPreference(context, resource) == REMOTE) {
// mark it as 'PROFILE_SPECIFIC' config, it has higher priority,
// will override the none profile specific config.
// fixed https://github.com/alibaba/spring-cloud-alibaba/issues/2455
@ -118,14 +113,48 @@ public class NacosConfigDataLoader implements ConfigDataLoader<NacosConfigDataRe
return options.toArray(new Option[0]);
}
private ConfigPreference getPreference(ConfigDataLoaderContext context,
NacosConfigDataResource resource) {
Binder binder = context.getBootstrapContext().get(Binder.class);
ConfigPreference preference = binder
.bind("spring.cloud.nacos.config.preference", ConfigPreference.class)
.orElse(LOCAL);
String specificPreference = resource.getConfig().getPreference();
if (specificPreference != null) {
try {
preference = ConfigPreference.valueOf(specificPreference.toUpperCase());
}
catch (IllegalArgumentException ignore) {
// illegal preference value, just ignore.
log.warn(String.format(
"illegal preference value: %s, using default preference: %s",
specificPreference, preference));
}
}
return preference;
}
private List<PropertySource<?>> pullConfig(ConfigService configService, String group,
String dataId, String suffix, long timeout)
throws NacosException, IOException {
String config = configService.getConfig(dataId, group, timeout);
logLoadInfo(group, dataId, config);
return NacosDataParserHandler.getInstance().parseNacosData(dataId, config,
suffix);
}
private void logLoadInfo(String group, String dataId, String config) {
if (config != null) {
log.info(String.format(
"[Nacos Config] Load config[dataId=%s, group=%s] success", dataId,
group));
}
else {
log.warn(String.format("[Nacos Config] config[dataId=%s, group=%s] is empty",
dataId, group));
}
}
protected <T> T getBean(ConfigDataLoaderContext context, Class<T> type) {
if (context.getBootstrapContext().isRegistered(type)) {
return context.getBootstrapContext().get(type);

@ -67,6 +67,8 @@ public class NacosConfigDataLocationResolver
private static final String REFRESH_ENABLED = "refreshEnabled";
private static final String PREFERENCE = "preference";
public NacosConfigDataLocationResolver(Log log) {
this.log = log;
}
@ -166,12 +168,17 @@ public class NacosConfigDataLocationResolver
location.isOptional(), profiles, log,
new NacosItemConfig().setGroup(groupFor(uri, properties))
.setDataId(dataIdFor(uri)).setSuffix(suffixFor(uri, properties))
.setRefreshEnabled(refreshEnabledFor(uri, properties)));
.setRefreshEnabled(refreshEnabledFor(uri, properties))
.setPreference(preferenceFor(uri)));
result.add(resource);
return result;
}
private String preferenceFor(URI uri) {
return getQueryMap(uri).get(PREFERENCE);
}
private URI getUri(ConfigDataLocation location, NacosConfigProperties properties) {
String path = location.getNonPrefixedValue(getPrefix());
if (StringUtils.isBlank(path)) {

@ -105,16 +105,18 @@ public class NacosConfigDataResource extends ConfigDataResource {
private String dataId;
private String suffix;
private boolean refreshEnabled;
private String preference;
public NacosItemConfig() {
}
public NacosItemConfig(String group, String dataId, String suffix,
boolean refreshEnabled) {
boolean refreshEnabled, String preference) {
this.group = group;
this.dataId = dataId;
this.suffix = suffix;
this.refreshEnabled = refreshEnabled;
this.preference = preference;
}
public NacosItemConfig setGroup(String group) {
@ -137,6 +139,11 @@ public class NacosConfigDataResource extends ConfigDataResource {
return this;
}
public NacosItemConfig setPreference(String preference) {
this.preference = preference;
return this;
}
public String getGroup() {
return group;
}
@ -153,6 +160,10 @@ public class NacosConfigDataResource extends ConfigDataResource {
return refreshEnabled;
}
public String getPreference() {
return preference;
}
@Override
public boolean equals(Object o) {
if (this == o) {
@ -165,19 +176,20 @@ public class NacosConfigDataResource extends ConfigDataResource {
return refreshEnabled == that.refreshEnabled
&& Objects.equals(group, that.group)
&& Objects.equals(dataId, that.dataId)
&& Objects.equals(suffix, that.suffix);
&& Objects.equals(suffix, that.suffix)
&& Objects.equals(preference, that.preference);
}
@Override
public int hashCode() {
return Objects.hash(group, dataId, suffix, refreshEnabled);
return Objects.hash(group, dataId, suffix, refreshEnabled, preference);
}
@Override
public String toString() {
return "NacosItemConfig{" + "group='" + group + '\'' + ", dataId='" + dataId
+ '\'' + ", suffix='" + suffix + '\'' + ", refreshEnabled="
+ refreshEnabled + '}';
+ refreshEnabled + ", preference=" + preference + '}';
}
}

@ -127,6 +127,8 @@ public class NacosContextRefresher
});
try {
configService.addListener(dataKey, groupKey, listener);
log.info("[Nacos Config] Listening config: dataId={}, group={}", dataKey,
groupKey);
}
catch (NacosException e) {
log.warn(String.format(

Loading…
Cancel
Save