一.nacos学习网站
中文社区:https://nacos.io/zh-cn/docs/quick-start.html
nacosexamples :https://github.com/nacos-group/nacos-examples
alibabanacos源码:https://github.com/alibaba/nacos
二.nacos安装
windows版本直接下载就能运行,单机运行startup.cmd时遇到个小坑,由于Nacos默认是以cluster集群的方式启动,而本地搭建通常是单机模式standalone,这里需手动改一下启动脚本startup.cmd中的启动模式。第27行改成:set MODE="standalone"
Linux版本的可以找下网上的docker安装nocos。
安装完成后默认端口是8848,用户密码都是nacos
三.搭建
新建spring boot項目,注意版本,nacos版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。
pom文件如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.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-test</artifactId>
<scope>test</scope>
</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>0.2.8</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-actuator</artifactId>
<version>0.2.8</version>
</dependency>
</dependencies>
启动类:
@SpringBootApplication
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosConfigSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConfigSpringbootApplication.class, args);
}
}
application.properties:
nacos.config.server-addr=127.0.0.1:8848
controller:
@Controller
@RequestMapping("/config")
public class ConfigController {
@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
private boolean useLocalCache;
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public boolean get() {
return useLocalCache;
}
}
启动nacos成功后打开地址:http://localhost:8848/nacos
编辑配置信息
这时候你在项目中就能够动态读取配置文件中的信息