nacos configuration deployment and management
configuration file
First create a new configuration file
- Data ID: the name of the configuration file (unique)
- Naming specification: service name-running environment-suffix name (generally use your yaml)
- Group: group name, generally use the default
- Configuration content: generally fill in the configuration that needs to be changed frequently, for example: some switches, parameters and the like
Configuration acquisition order:
项目启动
>> 读取bootstrap.yml文件
>> 读取nacos配置文件
>> 读取本地配置文件application.yml
>> 创建spring容器
>> 加载bean
Because the priority of reading the nacos configuration file is higher than that of the application, so the configuration information of nacos in the application cannot meet our needs, so spring provides a bootstrap file, its priority is higher than nacos, we are used to store the configuration information of nacos in bootstrap
- Introduce nacos configuration management client dependencies
<!-- nacos配置-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
- Create a bootstrap.yml file to configure nacos information
spring:
application:
name: userservice #服务名称
profiles:
active: dev #开发环境
cloud:
nacos:
config:
file-extension: yaml #文件后缀名
server-addr: localhost:8848 #nacos地址
- Get the corresponding configuration information through the @value annotation
@Component
@Data
public class Confix {
@Value("${pattern.dataformat}") //yyyy-MM-dd HH:mm:ss
private String dataformat;
}
@Autowired
private Confix confix;
@GetMapping("/get")
public String now(){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(confix.getDataformat()));
}
nacos configuration hot deployment
Hot deployment of configuration can be realized through @RefreshScope annotation. Bean modified by @RefreshScope annotation will be proxied by RefreshScope to realize hot loading of configuration and instance, that is, when the configuration changes, the bean can be refreshed without restarting the application related attribute value
@Component
@Data
@RefreshScope
public class Confix {
@Value("${pattern.dataformat}")
private String dataformat;
}
Use the @ConfigurationProperties annotation to mark the configuration class. After the configuration is released through Nacos, the configuration class will be rebind. At this time, the dynamic modification of the variable will take effect, and the used place will be injected through @Autowired.
@Component
@Data
@ConfigurationProperties(prefix = "pattern")
public class Confix {
private String dataformat;
}
前缀名(@ConfigurationProperties(prefix = "pattern"))和变量名(dataformat)拼接后要和配置文件一致