配置中心nacos 配置和使用流程
部署nacos
1、下载nacos镜像
docker pull nacos/nacos-server:2.0.2
如果已经有nacos 镜像可跳过此步骤
2、初始化nacos 依赖mysql数据库
执行nacos-mysql.sql 文件创建 mysql 数据表
3、启动nacos 镜像
docker run -d --name nacos --network host -e MODE=standalone -e NACOS_APPLICATION_PORT=18848 -e SPRING_DATASOURCE_PLATFORM=mysql -e MYSQL_SERVICE_HOST=mysql.java.com -e MYSQL_SERVICE_DB_NAME=nacos -e MYSQL_SERVICE_USER=user1 -e MYSQL_SERVICE_PASSWORD=pwd001 nacos/nacos-server
nacos 默认mysql 端口号 3306 如果需要自定义,只需要加 -e MYSQL_SERVICE_PORT=3307
springboot 中配置 nacos :
1、添加maven依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
2、创建yml文件
spring:
application:
name: example
cloud:
nacos:
config:
server-addr: nacos服务器ip:nacos域名(默认 8848)
spring:
application:
name: example
cloud:
nacos:
config:
file-extension: properties
enabled: true
prefix: example
profiles:
active: ${active.profile}
3、在nacos控制台创建配置
访问 http://nacos_ip:nacos_port/nacos
认证 nacos/nacos
配置管理>配置列表>点击"+"创建配置
DataId 为 配置文件中的 prefix + "-" + 配置文件中的 active + ".properties"
Group 为默认
配置内容选择 Properties
创建测试属性
xxx.xxx.field1=f1
xxx.xxx.field2=f2
4、在代码中使用配置
创建或修改统一配置类 Constants
在类上加注解 @Component @Data @RefreshScope
其中 非static 的动态字段 可直接在字段属性上添加注解@Value
@Value("${xxx.xxx.field1}")
private String config1;
对于static 的静态字段,需要在set方法上添加注解@Value
public static String FIELD2;
@Value("${xxx.xxx.field2}")
public void setField2(String field2){
FIELD2 = field2;
}