1、pom.xml添加以下依赖
<!-- ============Nacos依赖 ============ --> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-discovery-spring-boot-starter</artifactId> <version>0.2.3</version> </dependency> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-config-spring-boot-starter</artifactId> <version>0.2.3</version> </dependency>
2、bootstrap.yml
server:
port: 8080
spring:
application:
name: applicationName
3、application.yml
#nacos配置
nacos:
config:
server-addr: 127.0.0.1:8848
discovery:
server-addr: 127.0.0.1:8848
namespace: eb38c990-4109-4d6a-b216-8916b4dadae2 #指定命名空间
4、服务注册配置类
@Configuration public class NacosConfig { @Value("${server.port}") private int serverPort; @Value("${spring.application.name}") private String applicationName; @NacosInjected private NamingService namingService; @PostConstruct public void registerInstance() throws NacosException { namingService.registerInstance(applicationName, "127.0.0.1", serverPort); } }
5、NACOS-配置管理-配置列表-新建配置()
Data ID: EXAMPLE
Group: DEFAULT_GROUP
描述: Nacos初始化配置
Beta发布: 默认不要勾选。
配置格式: YAML
配置内容: MyName: nacos
project: springboot2-nacos
6、启动类配置
@SpringBootApplication @EnableDiscoveryClient @NacosPropertySource(dataId = "EXAMPLE", autoRefreshed = true) //新加nacos配置 public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); } }