1.引入Nacos 配置中心依赖
<!-- nacso 配置中心--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency>
2.在application.properties 配置文件中 添加 配置信息
spring.application.name=orderserver.port=8000spring.cloud.nacos.server-addr=127.0.0.1:8848spring.config.import=nacos:order.properties
spring.config.import 中的 “nacos:”字段是固定的
order.properties 是nacos 配置中心的Data ID
3.动态获得配置信息的代码
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Data
@Component
@ConfigurationProperties(prefix = "order") // 获得nacos中order开头的配置信息
public class OrderProperties {// 字段可以省略 prefix 中的部分private Integer timeOut;private Integer number;
}
4.模拟获得调用
@PostMapping("testOrder")public String testOrder(){System.out.println("orderTimeOut:"+orderProperties.getTimeOut()+" ;orderNumber;"+orderProperties.getNumber());return "这是获得订单接口";}
5.实现效果
控制台可准确打印配置信息 并且在nacos中改变配置信息后,无需重启服务可实时获得新的配置