nacos config 动态配置中心 - 快速部署

一. 安装nacos server

https://nacos.io/zh-cn/docs/quick-start.html

下载nacos压缩包,解压并执行startup.sh -m standalone

打开localhost:8848/nacos 控制后台查看服务启动情况

二. 控制后台新增配置


DataId: nacos定义的配置集

格式如下:

${prefix}-${spring.profiles.active}.${file-extension}
  • prefix默认为spring.application.name的值,也可以通过spring.cloud.nacos.config.prefix来配置

  • spring.profiles.active 环境配置,如果不存在则不参与拼接

  • file-extension文件格式 如properties
    在这里插入图片描述

三. 创建client,读取配置

  1. 创建bootstrap.properties,增加配置信息

    spring.application.name=my-config
    spring.cloud.nacos.config.server-addr=localhost:8848
    
  2. pom配置

    	 <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.3.2.RELEASE</version>
            </dependency>
        </dependencies>
    
  3. 创建Bootstrap类,并执行

    @SpringBootApplication
    public class ConfigApplication {
    
        private static ConfigurableEnvironment env;
    
        public static void main(String[] args) {
            SpringApplication sp = new SpringApplication(ConfigApplication.class);
            ConfigurableApplicationContext applicationContext = sp.run(args);
            env = applicationContext.getEnvironment();
    
            // 获取配置信息
            System.out.println(env.getProperty("show.title"));
        }
    }
    

    output:

    hello world
    
  4. @RefreshScope支持热更新

    使用@RefreshScope注解,使name字段支持动态刷新

    @Component
    @RefreshScope
    public class Book {
    
      @Value("${show.title}")
      private String name;
    
     	//省略getter setter方法
      ...
    }
    

    获取book的name属性

    Book book = applicationContext.getBean("book", Book.class);
    // 每隔一秒获取name属性一次
    while (true) {
      Thread.sleep(1000L);
      System.out.println(book.getName());
    }
    

    Output:

    影响力
    影响力
    影响力
    ## 修改show.title
    从删库到跑路
    从删库到跑路
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值