代码
代码地址
https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_Nacos/nacos-spring-boot-config-example
从官网弄来的,自己简单改了改 ,很简单的案例,
pom依赖
<properties>
<nacos-config-spring-boot.version>0.2.1</nacos-config-spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>${nacos-config-spring-boot.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-actuator</artifactId>
<version>${nacos-config-spring-boot.version}</version>
</dependency>
</dependencies>
application.properties
server.port=8080
nacos.config.server-addr=zjj101:8848
启动类
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Nacos 控制台添加配置:
* Data ID:example
* Group:DEFAULT_GROUP
* 配置内容:useLocalCache=true
*/
@SpringBootApplication
//指定nacos配置资源是 example
//autoRefreshed = true 代表自动刷新
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosConfigApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConfigApplication.class, args);
}
}
controller
@Controller
@RequestMapping("config")
public class ConfigController {
@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
private boolean useLocalCache;
/**
* 访问: localhost:8080/config/get
*/
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public boolean get() {
return useLocalCache;
}
}
nacos配置
useLocalCache: true
测试
postman调用接口: get请求 localhost:8080/config/get 即可看到效果
你在nacos-server修改完了之后,再访问上面的接口就能看到最新的内容了