springboot集成nacos并实现自动刷新

目录

1.说明

2.示例

3.自动刷新的注意点


1.说明

springboot项目中存在好多配置文件,比如配置数据信息,redis信息等等,配置文件可以直接放在代码,也可以放在像nacos这样的组件中,实现动态的管理,修改配置文件后不用进行项目的重启,直接可以实现自动刷新。

官网地址:

Nacos Spring Boot 快速开始

2.示例

①引入依赖

引入的nacos依赖要注意和springboot依赖适配。

        
            com.alibaba.boot
            nacos-config-spring-boot-starter
            0.2.5
        
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.10.RELEASE
         
    

 ②在nacos中添加配置文件

本地启动nacos之后,打开nacos画面,账号和密码都是nacos,如下:

springboot集成nacos并实现自动刷新_第1张图片

新建命名空间

 可以根据情况选择是否要创建命名空间,默认的命名空间是public。springboot集成nacos并实现自动刷新_第2张图片

 新建配置

在配置管理中,选择配置列表,然后选择新建配置所在的命名空间,点击右侧的加号,新建配置

springboot集成nacos并实现自动刷新_第3张图片

 输入配置文件的data id,data id就是配置文件的名字,在springboot项目中根据data id引入此配置文件。

group默认是DEFAULT_GROUP,可以设置成其他的,一般会设置为dev、test、prod,分别对应开发环境,测试环境及生产环境。
配置文件的格式一般是yaml或者时properities。

在配置文件内容中写入配置信息。

springboot集成nacos并实现自动刷新_第4张图片

 ③在springboot项目中引入配置

(1)在springboot项目的配置文件中添加nacos配置信息

配置nacos地址及命名空间,如果新创建了命名空间,需要指定一下命名空间id

nacos.config.server-addr=http://192.168.8.178:8848
#nacos.config.auto-refresh=true
nacos.config.namespace=5776702f-a25a-42f4-89d9-31114cfe160f

(2)在启动类中添加引入的nacos配置文件

通过NacosPropertySource注解,指定要引入配置文件的dataId及设置自动刷新为true。

package com.example.demo;

import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@MapperScan("com.example.demo.mapper")
@NacosPropertySource(dataId = "application",autoRefreshed = true)
@NacosPropertySource(dataId = "demo1",autoRefreshed = true)
@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

 (3)在程序中引入配置文件中的项目值

在程序中通过NacosValue引入配置文件中的项目内容,通过value属性指定项目id并设置自动刷新

    @NacosValue(value = "${server.name}",autoRefreshed = true)
    private String name;
    @NacosValue(value = "${student.id}",autoRefreshed = true)
    private String idInfo;
    @NacosValue(value="${student.name}",autoRefreshed = true)
    private String nameInfo;

 (4)启动项目

启动项目之后,就发现可以引用到配置文件中的内容,并且在nacos画面中修改了配置文件中项目的值,再次发起请求,发现代码中引用的值也会自动刷新。

3.自动刷新的注意点

①必须在启动类中引入配置文件时,设置自动刷新为true。

②必须在程序引用配置文件中的项目时,设置自动刷新为true。

③配置文件中的自动刷新可以不进行设置。

你可能感兴趣的:(spring,boot,java,spring)