Nacos系列——配置的创建与获取
- 配置的创建与获取
- 本文资源
- 官方文档
- 创建配置
- 获取Nacos配置
- 程序目录
- 1.引入依赖
- 完整pom
- 2.设置yaml
- 3.配置读取类NacosBasedProperties
- 4.构建日志打印工具LoggerUtil
- 5.构建Nacos基础服务类
- 实现
- 6.构建自动化任务
- 实现
- 结果
配置的创建与获取
本文资源
https://gitee.com/giteeforsyf/spring-cloud-formatter
选择下载:Nacos-easy
官方文档
https://nacos.io/zh-cn/docs/v2/guide/user/sdk.html
创建配置
- 点击配置管理
- 点击配置列表
- 选择右侧加号
- 设置配置的Data ID
- 设置配置的分组(默认为DEFAULT_GROUP)
- 设置配置内容(内容要匹配配置格式)
- 保存即可
如下我创建了test01配置
发布后入如下:
获取Nacos配置
这里仅需要一个简单的SpringBoot工程即可,如果您下载了对应的资源,那么仅需要查看资源内部README文档进行对应修改即可,下面我们将从0构建Nacos-easy
程序目录
1.引入依赖
<!-- 引入依赖-->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>2.1.0</version>
</dependency>
完整pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.fly</groupId>
<artifactId>Nacos-easy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Nacos-easy</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 引入依赖-->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.设置yaml
其中:
- serverAddr:你的nacos地址
- dataId: 配置的Data ID
- group:配置的组名称,默认为DEFAULT_GROUP
- timeout:连接超时时间
server:
port: 8889
nacos:
conf:
# 配置Nacos的地址
serverAddr: 192.168.31.149:8848
# 配置 ID,采用类似 package.class(如com.taobao.tc.refund.log.level)的命名规则保证全局唯一性,
# class 部分建议是配置的业务含义。全部字符小写。只允许英文字符和 4 种特殊字符("."、":"、"-"、"_"),不超过 256 字节
dataId: test01
# 配置分组,建议填写产品名:模块名(Nacos:Test)保证唯一性,默认:DEFAULT_GROUP
# 只允许英文字符和4种特殊字符("."、":"、"-"、"_"),不超过128字节。
group: DEFAULT_GROUP
# 读取配置超时时间,单位 ms,推荐值 3000。
timeout: 3000
3.配置读取类NacosBasedProperties
package cn.fly.nacoseasy.properties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author Syf200208161018
* @date 2022/12/18 15:56
* @ClassName:NacosBasedProperties
* @Effect:NacosBasedProperties is used for 获取yaml中的配置参数
*/
@ConfigurationProperties("nacos.conf")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NacosBasedProperties {
private String serverAddr;
private String dataId;
private String group;
private Long timeout;
}
4.构建日志打印工具LoggerUtil
package cn.fly.nacoseasy.utils;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Map;
/**
* @author Syf200208161018
* @date 2022/12/18 16:04
* @ClassName:LoggerUtil
* @Effect:LoggerUtil is used for
*/
@Slf4j
public class LoggerUtil {
/**
* 格式化日志打印,建议将logMap的第一个键值对设置为主题
*/
public static void formatLog(Map<String, String> logMap) {
final ArrayList<String> keys = new ArrayList<>();
final ArrayList<String> values = new ArrayList<>();
//遍历
logMap.forEach((x, y) -> {
keys.add(x);
values.add(y);
});
int len = keys.size();
if (len == 0) {
log.warn("请设置日志打印内容");
} else if (len == 1) {
log.info("{}:{}", keys.get(0), values.get(0));
} else {
log.info("=============" + keys.get(0) + ":" + values.get(0) + "================");
for (int flag = 1; flag < len; flag++) {
log.info("{}:{}", keys.get(flag), values.get(flag));
}
log.info("=============" + keys.get(0) + ":" + values.get(0) + "================");
}
}
}
5.构建Nacos基础服务类
package cn.fly.nacoseasy.service;
import com.alibaba.nacos.api.exception.NacosException;
/**
* @author Syf200208161018
* @date 2022/12/18 15:48
* @ClassName:NacosService
* @Effect:NacosService is used for
*/
public interface NacosBasedService {
/**
* 拉群Nacos中的配置
*/
void getConfigurationFromNacos() throws NacosException;
}
实现
package cn.fly.nacoseasy.service.impl;
import cn.fly.nacoseasy.properties.NacosBasedProperties;
import cn.fly.nacoseasy.service.NacosBasedService;
import cn.fly.nacoseasy.utils.LoggerUtil;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Properties;
/**
* @author Syf200208161018
* @date 2022/12/18 15:48
* @ClassName:NacosBasedServiceImpl
* @Effect:NacosBasedServiceImpl is used for 各类Nacos基础服务
*/
@Service
@EnableConfigurationProperties(NacosBasedProperties.class)
public class NacosBasedServiceImpl implements NacosBasedService {
@Autowired
private NacosBasedProperties basedProperties;
@Override
public void getConfigurationFromNacos() throws NacosException {
final HashMap<String, String> data = new HashMap<>();
Properties properties = new Properties();
properties.put("serverAddr", basedProperties.getServerAddr());
ConfigService configService = NacosFactory.createConfigService(properties);
String content = configService.getConfig(basedProperties.getDataId(), basedProperties.getGroup(), basedProperties.getTimeout());
data.put("Nacos配置", "");
data.put("配置内容", content);
LoggerUtil.formatLog(data);
}
}
6.构建自动化任务
package cn.fly.nacoseasy.service;
import org.springframework.boot.CommandLineRunner;
/**
* @author Syf200208161018
* @date 2022/12/18 15:44
* @ClassName:AutoService
* @Effect:AutoService is used for
*/
public interface AutoService extends CommandLineRunner {
}
实现
package cn.fly.nacoseasy.service.impl;
import cn.fly.nacoseasy.service.AutoService;
import cn.fly.nacoseasy.service.NacosBasedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
/**
* @author Syf200208161018
* @date 2022/12/18 15:44
* @ClassName:AutoServiceImpl
* @Effect:AutoServiceImpl is used for
*/
@Service
@Order(1)
public class AutoServiceImpl implements AutoService {
@Autowired
private NacosBasedService basedService;
@Override
public void run(String... args) throws Exception {
basedService.getConfigurationFromNacos();
}
}
结果
如果我们增加新的配置只需要在yaml中进行修改即可,输出就会改变了
如下: