欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > [0629].第29节:配置中心业务规则与动态刷新

[0629].第29节:配置中心业务规则与动态刷新

2025/12/8 21:36:46 来源:https://blog.csdn.net/weixin_43783284/article/details/144330596  浏览:    关键词:[0629].第29节:配置中心业务规则与动态刷新

我的后端学习大纲

SpringCloud学习大纲


1、编码实现3377服务:

1.1.建module:

在这里插入图片描述
在这里插入图片描述


1.2.改pom:

在这里插入图片描述

1.3.写YML:

1.Nacos同Consul一样,在项目初始化时,要保证先从配置中心进行配置拉取,拉取配置之后,才能保证项目的正常启动为了满足动态刷新和全局广播通知,springboot中配置文件的加载是存在优先级顺序的,bootstrap优先级高于application

a.bootstrap.properties:

  • 1.必须使用bootstrap.properties配置文件来配置Nacos Server
# nacos配置
spring:application:name: nacos-config-clientcloud:nacos:discovery:server-addr: localhost:8848 #Nacos服务注册中心地址config:server-addr: localhost:8848 #Nacos作为配置中心地址file-extension: yaml #指定yaml格式的配置# nacos端配置文件DataId的命名规则是:
# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# 本案例的DataID是:nacos-config-client-dev.yaml

b.application:

  • 1.与Nacos无关的配置写在Application中:
server:port: 3377spring:profiles:active: dev # 表示开发环境#active: prod # 表示生产环境#active: test # 表示测试环境

1.4.主启动:

package com.atguigu.cloudalibaba;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@EnableDiscoveryClient
@SpringBootApplication
public class NacosConfigClient3377{public static void main(String[] args){SpringApplication.run(NacosConfigClient3377.class,args);}
}

1.5.业务类:

package com.atguigu.cloud.controller;import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RefreshScope //在控制器类加入@RefreshScope注解使当前类下的配置支持Nacos的动态刷新功能。
public class NacosConfigClientController
{@Value("${config.info}")private String configInfo;@GetMapping("/config/info")public String getConfigInfo() {return configInfo;}
}

@RefreshScope 注解来实现配置的自动更新


2、在Nacos中的匹配规则:

2.1.设置DataId理论:

a.官网介绍:

  • 1.Nacos中的DataId的组成格式及与SpringBoot配置文件匹配的规则:

最后公式:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

b.配置DataId实操:

  • 公式:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
  • prefix默认值:spring.application.name的值
  • spring.profiles.active即为当前环境对应的profile,可以通过配置项:spring.profiles.active来配置
  • file-extension为配置文件的数据格式
    在这里插入图片描述

2.2.创建配置:

在这里插入图片描述

2.3.配置DataId和对应文件:

  • Data ID:nacos-config-client-dev.yaml
    在这里插入图片描述

说明:

  • 配置更改后可以自动刷新
  • Nacos会记录配置文件的历史版本,默认保留30天,此外还有一键回滚的功能,回滚也会触发配置更新

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词