1.Nacos安装
参考:docker快速部署nacos - jupiter's blog (inat.top)
2.SpringBoot集成Nacos作为配置中心
2.1 引入依赖
- 必要依赖
<!--nacos配置中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2023.0.1.0</version>
</dependency>
<!-- spring-cloud-starter-bootstrap -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>4.1.2</version>
</dependency>
- JSON转换依赖(测试用,可选)
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.28</version>
</dependency>
2.2 nacos新建命名空间和配置文件
- 配置文件内容
# 注入字符串
stringConfig: nacosStringConfig
# 注入数组
arrayConfig: aaa,bbb,ccc
# 注入list
listConfig: aaa,bbb,ccc
2.3 bootstrap.yml增加配置
spring:
cloud:
nacos:
username: nacos
password: nacos123
config:
namespace: 4ee219bc-2c01-4598-9719-bec80a57ce2f
server-addr: 192.168.124.10:8848
extension-configs:
- {data-id: "project-basic.yaml", group: "dev", refresh: "true"}
2.4 配置映射类
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@RefreshScope
@Data
public class ProjectBasicConfig {
@Value("${stringConfig:}")
private String stringConfig;
@Value("${arrayConfig:}")
private String[] arrayConfig;
@Value("#{'${listConfig:}'.empty ? null : '${listConfig:}'.split(',')}")
private List<String> listConfig;
}
2.5 配置映射使用测试
@RestController
public class TestController {
@Resource
private ProjectBasicConfig projectBasicConfig;
@GetMapping("/")
public String testNacosConfig() {
return "stringConfig=" + projectBasicConfig.getStringConfig()
+ ",arrayConfig=" + JSONUtil.toJsonStr(projectBasicConfig.getArrayConfig())
+ ",listConfig=" +JSONUtil.toJsonStr(projectBasicConfig.getListConfig());
}
}
评论 (0)