目录
- 1. 说明
- 2. 截图示例
- 3. 代码示例
- 4. 关键代码
1. 说明
- 1.springboot读取服务器上nacos配置会在客户端本地缓存配置。
- 2.在没有服务器nacos配置的情况下,可以在本地新建一个目录,里面放入配置文件,也可以读到配置。
- 3.注意不同版本的nacos配置目录默认不一样。请注意nacos和springboot的版本号。
- 4.当远程连不上服务器的nacos时,可以在本地放个缓存来启动项目。
2. 截图示例
3. 代码示例
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>Learn</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.5.6</version></dependency><!-- 在pom.xml中添加Nacos Spring Boot Starter依赖 --><dependency><groupId>com.alibaba.boot</groupId><artifactId>nacos-config-spring-boot-starter</artifactId><version>0.2.12</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.34</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.52</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
spring:cloud:nacos:config:# 本地没有这个nacos,随便写的server-addr: 127.0.0.1:8848group: DEFAULT_GROUPfile-extension: yaml
package com.learn;import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** @date 2024/12/11* @description*/
@SpringBootApplication
@NacosPropertySource(dataId = "application.yaml", autoRefreshed = true)
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
package com.learn.controller;import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/example")
public class ExampleController {@NacosValue("${test.name}")private String name;@GetMapping("/test")public String test() {return name;}
}
4. 关键代码
- 1.读取本地文件
- 2.文件存放位置
- 3.application配置内容
test:name: zhangsan