add nacos examples

pull/2597/head
lixiaoshuang 3 years ago committed by chengpu.rzh
parent 017bce3794
commit 04a55e4790

@ -24,17 +24,11 @@
spring.application.name=nacos-config-example
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
3. 完成上述两步后,应用会从 Nacos Config 中获取相应的配置,并添加在 Spring Environment 的 PropertySources 中。这里我们使用 @Value 注解来将对应的配置注入到 SampleController 的 userName 和 age 字段,并添加 @RefreshScope 打开动态刷新功能
@RefreshScope
class SampleController {
@Value("${user.name}")
String userName;
@Value("${user.age}")
int age;
}
3. 完成上述两步后,应用会从 Nacos Config 中获取相应的配置,并添加在 Spring Environment 的 PropertySources 中。假设我们通过 Nacos 配置中心保存 Nacos 的部分配置,有以下四种例子:
- BeanAutoRefreshConfigExample: 通过将配置信息配置为bean支持配置变自动刷新的例子
- ConfigListenerExample: 监听配置信息的例子
- DockingInterfaceExample: 对接 nacos 接口,通过接口完成对配置信息增删改查的例子
- ValueAnnotationExample: 通过 @Value 注解进行配置信息获取的例子
### 启动 Nacos Server 并添加配置
@ -50,7 +44,7 @@
3. 在命令行执行如下命令,向 Nacos Server 中添加一条配置。
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=17"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serveraddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"
**注:你也可以使用其他方式添加,遵循 HTTP API 规范即可,若您使用的 Nacos 版本自带控制台,建议直接使用控制台进行配置**
@ -59,11 +53,12 @@
dataId 为 nacos-config-example.properties
group 为 DEFAULT_GROUP
内容如下
内容如下:
user.id=1
user.name=james
user.age=17
spring.cloud.nacos.config.serveraddr=127.0.0.1:8848
spring.cloud.nacos.config.prefix=PREFIX
spring.cloud.nacos.config.group=GROUP
spring.cloud.nacos.config.namespace=NAMESPACE
### 应用启动
@ -81,18 +76,18 @@
### 验证
#### 验证自动注入
在浏览器地址栏输入 `http://127.0.0.1:18084/user`,并点击调转,可以看到成功从 Nacos Config Server 中获取了数据。
在浏览器地址栏输入 `http://127.0.0.1:18084/nacos/bean`,并点击调转,可以看到成功从 Nacos Config Server 中获取了数据。
![get](https://cdn.nlark.com/lark/0/2018/png/54319/1536986328663-5e3503c2-7e14-4c56-b5f9-72fecc6898d2.png)
![](https://tva1.sinaimg.cn/large/e6c9d24ely1h29htdsg18j20jc0aigma.jpg)
#### 验证动态刷新
1. 执行如下命令,修改 Nacos Server 端的配置数据
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=18"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serveraddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=DEFAULT_GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"
2. 在浏览器地址栏输入 `http://127.0.0.1:18084/user`,并点击调转,可以看到应用从 Nacos Server 中获取了最新的数据age 变成了 18
2. 在浏览器地址栏输入 `http://127.0.0.1:18084/nacos/bean`,并点击调转,可以看到应用从 Nacos Server 中获取了最新的数据group 变成了 DEFAULT_GROUP
![refresh](https://cdn.nlark.com/lark/0/2018/png/54319/1536986336535-c0efdf6d-a5d3-4f33-8d26-fe3a36cdacf6.png)
![](https://tva1.sinaimg.cn/large/e6c9d24ely1h29hzf0ic4j20ks0b4mxy.jpg)
## 原理
@ -165,9 +160,9 @@ Spring Boot 2.x 可以通过访问 http://127.0.0.1:18084/actuator/nacosconfig
配置项|key|默认值|说明
----|----|-----|-----
服务端地址|spring.cloud.nacos.config.server-addr||服务器ip和端口
DataId前缀|spring.cloud.nacos.config.prefix|${spring.application.name}|
DataId前缀|spring.cloud.nacos.config.prefix|${spring.application.name}|DataId的前缀默认值为应用名称
Group|spring.cloud.nacos.config.group|DEFAULT_GROUP|
dataID后缀及内容文件格式|spring.cloud.nacos.config.file-extension|properties|dataId的后缀同时也是配置内容的文件格式目前只支持 properties
DataId后缀及内容文件格式|spring.cloud.nacos.config.file-extension|properties|DataId的后缀同时也是配置内容的文件格式目前只支持 properties
配置内容的编码方式|spring.cloud.nacos.config.encode|UTF-8|配置的编码
获取配置的超时时间|spring.cloud.nacos.config.timeout|3000|单位为 ms
配置的命名空间|spring.cloud.nacos.config.namespace||常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源隔离等。

@ -23,18 +23,12 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
spring.application.name=nacos-config-example
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
3. After completing the above two steps, the application will get the externalized configuration from Nacos Server and put it in the Spring Environment's PropertySources.We use the @Value annotation to inject the corresponding configuration into the userName and age fields of the SampleController, and add @RefreshScope to turn on dynamic refresh .
@RefreshScope
class SampleController {
@Value("${user.name}")
String userName;
@Value("${user.age}")
int age;
}
3. After completing the above two steps, the application will obtain the corresponding configuration from Nacos Config and add it to the PropertySources of Spring Environment. Suppose we save part of the configuration of Nacos through the Nacos configuration center, there are the following four examples:
- BeanAutoRefreshConfigExample: An example that supports automatic refresh of configuration changes by configuring configuration information as beans
- ConfigListenerExample: Example of listening configuration information
- DockingInterfaceExample: An example of docking the nacos interface and completing the addition, deletion, modification and checking of configuration information through the interface
- ValueAnnotationExample: An example of obtaining configuration information through @Value annotation
### Start Nacos Server
@ -49,8 +43,8 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
2. Windows , execute `cmd startup.cmd -m standalone`
3. Execute the following command to add a configuration to Nacos Server.
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=17"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serveraddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"
**Note: You can also add it in other ways. If you are using the Nacos version with its own console, it is recommended to configure it directly using the console.**
@ -60,11 +54,12 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
dataId is nacos-config-example.properties
group is DEFAULT_GROUP
content is
content is:
user.id=1
user.name=james
user.age=17
spring.cloud.nacos.config.serveraddr=127.0.0.1:8848
spring.cloud.nacos.config.prefix=PREFIX
spring.cloud.nacos.config.group=GROUP
spring.cloud.nacos.config.namespace=NAMESPACE
### Start Application
@ -82,19 +77,18 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
### Verification
#### Automatic Injection
Enter `http://127.0.0.1:18084/user` in the browser address bar and click Go to, we can see the data successfully obtained from Nacos Config Server.
Enter `http://127.0.0.1:18084/nacos/bean` in the browser address bar and click Go to, we can see the data successfully obtained from Nacos Config Server.
![get](https://cdn.nlark.com/lark/0/2018/png/54319/1536986328663-5e3503c2-7e14-4c56-b5f9-72fecc6898d2.png)
![](https://tva1.sinaimg.cn/large/e6c9d24ely1h29htdsg18j20jc0aigma.jpg)
#### Dynamic Refresh
1. Run the following command to modify the configuration data on the Nacos Server side.
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=18"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serveraddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=DEFAULT_GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"
2. Enter `http://127.0.0.1:18084/user` in the browser address bar and click Go to,
We can see that the app got the latest data from Nacos Server and the age becomes 18.
2. Enter `http://127.0.0.1:18084/nacos/bean` in the address bar of the browser, and click Flip, you can see that the application has obtained the latest data from Nacos Server, and the group has become DEFAULT_GROUP.
![refresh](https://cdn.nlark.com/lark/0/2018/png/54319/1536986336535-c0efdf6d-a5d3-4f33-8d26-fe3a36cdacf6.png)
![](https://tva1.sinaimg.cn/large/e6c9d24ely1h29hzf0ic4j20ks0b4mxy.jpg)
## Principle
@ -169,18 +163,19 @@ As shown in the figure above, Sources indicates which Nacos Config configuration
Configuration item|key|default value|Description
----|----|-----|-----
server address|spring.cloud.nacos.config.server-addr||
DataId prefix|spring.cloud.nacos.config.prefix||spring.application.name
server address|spring.cloud.nacos.config.server-addr||server id and port
DataId prefix|spring.cloud.nacos.config.prefix|${spring.application.name}|the prefix of nacos config DataId
Group|spring.cloud.nacos.config.group|DEFAULT_GROUP|
dataID suffix|spring.cloud.nacos.config.file-extension|properties|the suffix of nacos config dataId, also the file extension of config content.
DataID suffix|spring.cloud.nacos.config.file-extension|properties|the suffix of nacos config DataId, also the file extension of config content.
encoding |spring.cloud.nacos.config.encode|UTF-8|Content encoding
timeout|spring.cloud.nacos.config.timeout|3000|Get the configuration timeout period,unit is ms
namespace|spring.cloud.nacos.config.namespace||One of the common scenarios is the separation of the configuration of different environments, such as the development of the test environment and the resource isolation of the production environment.
AccessKey|spring.cloud.nacos.config.access-key||
SecretKey|spring.cloud.nacos.config.secret-key||
context-path|spring.cloud.nacos.config.context-path||Relative path of the server API
endpoint|spring.cloud.nacos.config.endpoint|UTF-8|The domain name of a service, through which the server address can be dynamically obtained.
endpoint|spring.cloud.nacos.config.endpoint||The domain name of a service, through which the server address can be dynamically obtained.
refresh|spring.cloud.nacos.config.refresh.enabled|true|enable auto refresh
cluster name|spring.cloud.nacos.config.cluster-name||

@ -16,218 +16,21 @@
package com.alibaba.cloud.examples;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import com.alibaba.cloud.examples.model.NacosConfigInfo;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* @author xiaojing, Jianwei Mao
*/
@SpringBootApplication
@EnableConfigurationProperties(NacosConfigInfo.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public UserConfig userConfig() {
return new UserConfig();
}
}
@ConfigurationProperties(prefix = "user")
class UserConfig {
private int age;
private String name;
private String hr;
private Map<String, Object> map;
private List<User> users;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public String getHr() {
return hr;
}
public void setHr(String hr) {
this.hr = hr;
}
@Override
public String toString() {
return "UserConfig{" + "age=" + age + ", name='" + name + '\'' + ", map=" + map
+ ", hr='" + hr + '\'' + ", users=" + users + '}';
}
public static class User {
private String name;
private String hr;
private String avg;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHr() {
return hr;
}
public void setHr(String hr) {
this.hr = hr;
}
public String getAvg() {
return avg;
}
public void setAvg(String avg) {
this.avg = avg;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", hr=" + hr + ", avg=" + avg + '}';
}
}
}
@Component
class SampleRunner implements ApplicationRunner {
@Autowired
private NacosConfigManager nacosConfigManager;
@Override
public void run(ApplicationArguments args) throws Exception {
nacosConfigManager.getConfigService().addListener(
"nacos-config-custom.properties", "DEFAULT_GROUP", new Listener() {
/**
* Callback with latest config data.
* @param configInfo latest config data for specific dataId in Nacos
* server
*/
@Override
public void receiveConfigInfo(String configInfo) {
Properties properties = new Properties();
try {
properties.load(new StringReader(configInfo));
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("config changed: " + properties);
}
@Override
public Executor getExecutor() {
return null;
}
});
}
}
@RestController
@RefreshScope
class SampleController {
@Autowired
UserConfig userConfig;
@Autowired
private NacosConfigManager nacosConfigManager;
@Autowired
private Environment environment;
@Value("${user.name:zz}")
String userName;
@Value("${user.age:25}")
Integer age;
@RequestMapping("/user")
public String simple() {
return "Hello Nacos Config!" + "Hello " + userName + " " + age + " [UserConfig]: "
+ userConfig + "!" + nacosConfigManager.getConfigService();
}
@RequestMapping("/get/{name}")
public String getValue(@PathVariable String name) {
return String.valueOf(environment.getProperty(name));
}
@RequestMapping("/bool")
public boolean bool() {
return (Boolean) (userConfig.getMap().get("2"));
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

@ -0,0 +1,35 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.examples.configuration;
import com.alibaba.cloud.examples.model.NacosConfigInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Bean definition
*
* @author lixiaoshuang
*/
@Configuration
public class BeanConfiguration {
@Bean
public NacosConfigInfo nacosConfigInfo() {
return new NacosConfigInfo();
}
}

@ -0,0 +1,49 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.examples.example;
import com.alibaba.cloud.examples.model.NacosConfigInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* Dynamic bean refresh example
*
* @author lixiaoshuang
*/
@RestController
@RequestMapping("/nacos/bean")
public class BeanAutoRefreshConfigExample {
@Autowired
private NacosConfigInfo nacosConfigInfo;
@GetMapping
public Map<String, String> getConfigInfo() {
Map<String, String> result = new HashMap<>();
result.put("serveraddr", nacosConfigInfo.getServeraddr());
result.put("prefix", nacosConfigInfo.getPrefix());
result.put("group", nacosConfigInfo.getGroup());
result.put("namespace", nacosConfigInfo.getNamespace());
return result;
}
}

@ -0,0 +1,63 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.examples.example;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Configuration listener example.
*
* @author lixiaoshuang
*/
@Component
public class ConfigListenerExample {
public static final String DATA_ID = "nacos-config-example.properties";
public static final String GROUP = "DEFAULT_GROUP";
@Autowired
private NacosConfigManager nacosConfigManager;
@PostConstruct
public void init() throws NacosException {
ConfigService configService = nacosConfigManager.getConfigService();
configService.addListener(DATA_ID, GROUP, new Listener() {
@Override
public Executor getExecutor() {
return Executors.newSingleThreadExecutor();
}
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println("[dataId]:[" + DATA_ID + "],Configuration changed to:" + configInfo);
}
});
}
}

@ -0,0 +1,128 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.examples.example;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Executor;
/**
* Example of docking with Nacos interface
*
* @author lixiaoshuang
*/
@RestController
@RequestMapping("nacos")
public class DockingInterfaceExample {
public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
@Autowired
private NacosConfigManager nacosConfigManager;
/**
* Get configuration information
*
* @param dataId
* @param group
* @return
* @throws NacosException
*/
@RequestMapping("getConfig")
public String getConfig(@RequestParam("dataId") String dataId,
@RequestParam(value = "group", required = false) String group) throws NacosException {
if (StringUtils.isEmpty(group)) {
group = DEFAULT_GROUP;
}
ConfigService configService = nacosConfigManager.getConfigService();
return configService.getConfig(dataId, group, 2000);
}
/**
* Publish configuration
*
* @param dataId
* @param group
* @param content
* @return
* @throws NacosException
*/
@RequestMapping("publishConfig")
public boolean publishConfig(@RequestParam("dataId") String dataId,
@RequestParam(value = "group", required = false) String group, @RequestParam("content") String content)
throws NacosException {
if (StringUtils.isEmpty(group)) {
group = DEFAULT_GROUP;
}
ConfigService configService = nacosConfigManager.getConfigService();
return configService.publishConfig(dataId, group, content);
}
/**
* Delete configuration
*
* @param dataId
* @param group
* @return
* @throws NacosException
*/
@RequestMapping("remoteConfig")
public boolean remoteConfig(@RequestParam("dataId") String dataId,
@RequestParam(value = "group", required = false) String group) throws NacosException {
if (StringUtils.isEmpty(group)) {
group = DEFAULT_GROUP;
}
ConfigService configService = nacosConfigManager.getConfigService();
return configService.removeConfig(dataId, group);
}
/**
* Add listener configuration information
*
* @param dataId
* @param group
* @throws NacosException
*/
@RequestMapping("listener")
public String listenerConfig(@RequestParam("dataId") String dataId,
@RequestParam(value = "group", required = false) String group) throws NacosException {
if (StringUtils.isEmpty(group)) {
group = DEFAULT_GROUP;
}
ConfigService configService = nacosConfigManager.getConfigService();
configService.addListener(dataId, group, new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println("[Listen for configuration changes]:" + configInfo);
}
});
return "Add Lister successfully!";
}
}

@ -0,0 +1,59 @@
/*
* Copyright 2013-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.examples.example;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* Use the @Value annotation to get configuration example
*
* @author lixiaoshuang
*/
@RestController
@RequestMapping("/nacos/annotation")
@RefreshScope
public class ValueAnnotationExample {
@Value("${spring.cloud.nacos.config.serveraddr:}")
private String serveraddr;
@Value("${spring.cloud.nacos.config.prefix:}")
private String prefix;
@Value("${spring.cloud.nacos.config.group:}")
private String group;
@Value("${spring.cloud.nacos.config.namespace:}")
private String namespace;
@GetMapping
public Map<String, String> getConfigInfo() {
Map<String, String> result = new HashMap<>();
result.put("serveraddr", serveraddr);
result.put("prefix", prefix);
result.put("group", group);
result.put("namespace", namespace);
return result;
}
}

@ -0,0 +1,78 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.examples.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
@ConfigurationProperties(prefix = "spring.cloud.nacos.config")
@RefreshScope
public class NacosConfigInfo {
/**
* Nacos server address
*/
private String serveraddr;
/**
* Data Id prefix
*/
private String prefix;
/**
* Nacos group
*/
private String group;
/**
* Nacos namespace
*/
private String namespace;
public String getServeraddr() {
return serveraddr;
}
public void setServeraddr(String serveraddr) {
this.serveraddr = serveraddr;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
}
Loading…
Cancel
Save