说说如何搭建与使用 Nacos 配置中心

1 Nacos 服务(Server)

从 Nacos 官网 下载 nacos-server-$version.zip 包,解压到指定目录。

Windows 中,打开解压目录下的 \bin\startup.cmd 启动服务。

Nacos 服务占用内存近 2G,对资源要求很高。

启动成功后,Nacos 服务就运行起来了。在浏览器中输入 http://127.0.0.1:8848/nacos/index.html,就可以打开 Nacos 控制台:

使用默认账号密码(nacos/nacos),就可以登陆控制台:

2 Nacos 客户端

在基于 SpringBoot 微服务工程中,搭载 Nacos 客户端,实现配置管理。

(1)添加依赖

<!--nacos config-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>${nacos-config.version}</version>
</dependency>

(2)bootstrap.properties 中配置 Nacos server 的地址和应用名

spring:
  application:
    name: deniro-micro-service
  cloud:
    nacos:
      config:
        # nacos config center address
        server-addr: 127.0.0.1:8848
        group: productName.moduleName
        # config format
        file-extension: properties

这里配置的 spring.application.name,会作为 Nacos 配置管理 dataId 字段的一部分。dataId 的完整格式如下:

${prefix}-${spring.profile.active}.${file-extension}
符号名 说明
prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置
spring.profile.active 当前环境对应的 profile。当 spring.profile.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 p r e f i x . {prefix}. {file-extension}。
file-exetension 配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型。

(3)配置项

在实际的 Spring Bean 类中,加入业务工程所需要配置项。形如:

@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {

    @Value("${thirdIpAddress:127.0.0.1}")
    private String thirdIpAddress;
}

首先在业务类上加入 @RefreshScope,这样当配置中心的配置值发生变化时,业务类所引用的值就会自动更新。

接着通过 @Value 将外部的配置项值动态注入到该 Bean 中。通过冒号语法,可以给配置项指定一个默认值。

3 发布配置

发布配置有两种方式,一种是通过 HTTP 接口;另一种是通过配置中心。

3.1 HTTP 接口

使用 POST 方式请求以下地址:

http://xxx:8848/nacos/v1/cs/configs?dataId=net.deniro.cloud.service.properties&group=productName.moduleName&content=thirdIpAddress=192.168.3.8

这里的 dataId 命名规则为 spring.application.name+‘.properties’ ;group 就是 cloud.nacos.config.group; 最后一个 content 是实际的配置项。

请求成功后,就会返回 true。

3.2 配置中心

登录配置中心后,找到刚才提交的配置(或者新建配置)。

选择 Properties 格式,然后加入配置内容,保存即可。

保存后,客户端就会自动更新所对应的配置项的值。

这种方式的好处是可以同时加入多个配置项。

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/107281557