springCloud之配置中心(nacos的配置管理)
在Spring Cloud中使用Nacos作为配置中心,你需要做以下几步操作:
- 引入Nacos客户端依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
- 在
bootstrap.properties
或bootstrap.yml
中配置Nacos服务器地址和应用名:
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.application.name=my-application
- 在Nacos服务器端创建配置,配置格式可以是
Properties
、YAML
或JSON
等。 - 在应用中使用
@Value
注解或@ConfigurationProperties
注解来注入配置:
@Value("${my.config}")
private String myConfig;
// 或者
@ConfigurationProperties(prefix = "my")
@Component
public class MyConfigProperties {
private String config;
// getters and setters
}
- 在Nacos控制台修改配置后,应用会自动更新配置。
以下是一个简单的示例,演示如何在Spring Cloud应用中使用Nacos作为配置中心。
# bootstrap.yml
spring:
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
namespace: 4f32bb35-0a34-41d6-8997-314bb682cc72 # 如果有指定命名空间,需要添加此项
group: DEFAULT_GROUP
file-extension: yaml # 指定配置内容的格式,默认是properties
// 应用启动类或配置类
@SpringBootApplication
public class NacosConfigApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConfigApplication.class, args);
}
}
// 配置属性类
@Component
@ConfigurationProperties(prefix = "my")
public class MyConfig {
private String property;
// getters and setters
}
// 使用配置属性
@RestController
public class ConfigController {
@Autowired
private MyConfig myConfig;
@GetMapping("/config")
public String getConfig() {
return myConfig.getProperty();
}
}
确保Nacos服务器正常运行,并且应用配置中心信息正确。当你在Nacos控制台修改配置后,访问/config
接口,应该能看到更新后的配置值。
评论已关闭