废话不多说直接上代码
首先创建一个spring boot maven项目
-
pom文件增加依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>nacosDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>nacosDemo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
-
在application.properties文件中添加配置
spring.application.name=agent spring.cloud.nacos.config.server-addr=127.0.0.1:8848 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 //定义配置文件后缀为.properties spring.cloud.nacos.config.file-extension=properties //此处为自定义命名空间,下面会有说明 spring.cloud.nacos.config.namespace=29de6443-9f76-4c4b-9ff2-f754961365d4 //此处为自定义分组,下面有说明 spring.cloud.nacos.config.group=OLD_GROUP
-
在启动类里面加上
@EnableDiscoveryClient
-
在配置类上面添加实现当前类属性动态更新
@RefreshScope
package com.example.nacosdemo; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RefreshScope @RestController @EnableDiscoveryClient public class NacosDemoApplication { public static void main(String[] args) { SpringApplication.run(NacosDemoApplication.class, args); } @Value("${redis.host}") private String config; @RequestMapping("/getValue") public String getValue() { return config; } }
官网下载nacos-server,启动nacos
-
创建命名空间
-
创建dataid,配填写配置
完成以上操作即可顺利启动