Conan
Conan
发布于 2024-05-09 / 128 阅读
0
0

SpringBoot单体服务集成Nacos配置中心

Nacos官方文档:Nacos 融合 Spring Boot,成为注册配置中心 | Nacos

GIthub详细文档:spring boot 0.2.2 以及 0.1.2版本新功能使用手册 · nacos-group/nacos-spring-boot-project Wiki · GitHub

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.7</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

    <dependency>
      <groupId>com.alibaba.boot</groupId>
      <artifactId>nacos-config-spring-boot-starter</artifactId>
      <version>0.2.12</version>
    </dependency>

application.yml

nacos:
  config:
    bootstrap:
      enable: true
      log-enable: true
    server-addr: xxx:xxxx
    max-retry: 10
    config-retry-time: 1000
    # 主配置文件,必须要有的。
    data-id: hospital.dept.code
    type: yaml
    group: DEFAULT_GROUP
    # 开启nacos自动刷新,如果这个配置没有或者为false会导致配置不能自动刷新
    auto-refresh: true
    # 允许nacos服务端向本地同步配置
    enable-remote-sync-config: true
    # 必须要有data-id属性后,才能再ext-config中加其他配置
    ext-config:
      - data-id: city.id
        type: yaml
        group: DEFAULT_GROUP
        auto-refresh: true
        enable-remote-sync-config: true

只需要在配置文件中加上,Naocs的config配置即可,不需要再次在启动类上加。

使用:

@Data
@Configuration
@NacosConfigurationProperties(
    prefix = "city-id",
    dataId = "city.id",
    type = ConfigType.YAML,
    autoRefreshed = true)
public class NacosCityIdMap {
  private Map<String, String> map;
}

配置文件:

@Data
@Configuration
@NacosConfigurationProperties(
    prefix = "city-id",
    dataId = "city.id",
    type = ConfigType.YAML,
    autoRefreshed = true)
public class NacosCityIdMap {
  private Map<String, String> map;
}

可自动刷新;


评论