SpringBoot 使用 Nacos 作为配置中心和注册中心

1,417 阅读5分钟

Nacos 官方文档地址

1. Nacos 简介

1.1. 下载安装

在官方文档的快速开始目录下的Nacos文档中,就主要介绍了这部分内容。我们可以直接在2.下载源码或者安装包找到最新稳定版本下载,如下图所示:

在这里插入图片描述

点开最新稳定版本后,会看到很一个 Releases 列表,找到最新的非 BEAT 版本,目前最新稳定版本是 1.2.1,直接点击下载 zip 包,解压完就能使用。(类似于 Tomcat 的压缩包,Linux 版本和 Windows 版本都在一个压缩包中。)

在这里插入图片描述

我这里是 Windows 系统,解压安装到了 D 盘(这里需要注意的是安装路径中的目录不要有空格,否则会启动失败,黑窗口一闪而逝),在D:\nacos\bin下双击 startup.cmd 运行文件或者在命令行窗口执行启动命令:

cmd startup.cmd

服务启动成功如下图所示:

在这里插入图片描述

接下来就可以直接通过下面地址来访问控制台了,默认账号密码都是 nacos:

http://127.0.0.1:8848/nacos

1.2. 界面操作

我本地的项目名为 demo,所以直接新建了一个命名空间 demo,在 demo 下添加配置,其实就是把项目中的配置文件的内容复制粘贴 nacos 中,主要需要注意下 dataId 和 Group 的命名。添加完成后如下图所示:

在这里插入图片描述

在这里插入图片描述

2. 配置中心

接下来介绍 SpringBoot 项目使用 Nacos 作配置中心,在官方文档的快速开始目录下的Nacos Spring Boot文档中有简单介绍。

2.1. 添加依赖

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

文档中提示:版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。我的 SpringBoot 版本为 2.1.7.RELEASE,这里我选择引入目前最新的 0.2.7 版本。

2.2. 项目配置

关于 Nacos Spring Boot 的详细文档请参看:nacos-spring-boot-project。这里可以看到各版本的一些新增内容。下面列出官方给出的一些配置,可以参考以下配置参数进行设置:

# 开启配置预加载功能
nacos.config.bootstrap.enable=true
# 主配置 服务器地址
nacos.config.server-addr=192.168.16.104:8848
# 主配置 data-id
nacos.config.data-id=people
# 主配置 group-id
nacos.config.group=DEFAULT_GROUP
# 主配置 配置文件类型
nacos.config.type=properties
# 主配置 最大重试次数
nacos.config.max-retry=10
# 主配置 开启自动刷新
nacos.config.auto-refresh=true
# 主配置 重试时间
nacos.config.config-retry-time=2333
# 主配置 配置监听长轮询超时时间
nacos.config.config-long-poll-timeout=46000
# 主配置 开启注册监听器预加载配置服务(除非特殊业务需求,否则不推荐打开该参数)
nacos.config.enable-remote-sync-config=true

# 支持日志级别的加载时机
nacos.config.bootstrap.log-enable=true
# 支持配置 data-ids 的设置方式
nacos.config.data-ids=people,test
# 支持 nacos 1.2.0 新增的权限控制功能
nacos.config.username=nacos
nacos.config.password=nacos
# 允许nacos上的配置优先于本地配置
nacos.config.remote-first=true

ext-config[index] 的优先级,index 越小,优先级越高,从 0 开始。

nacos.config.ext-config[0].data-id=test
nacos.config.ext-config[0].group=DEFAULT_GROUP
nacos.config.ext-config[0].max-retry=10
nacos.config.ext-config[0].type=yaml
nacos.config.ext-config[0].auto-refresh=true
nacos.config.ext-config[0].config-retry-time=2333
nacos.config.ext-config[0].config-long-poll-timeout=46000
nacos.config.ext-config[0].enable-remote-sync-config=true

接下来说下我的配置。将 application-dev.yml 文件内容修改为:

nacos:
  config:
    bootstrap:
      enable: true
      log-enable: true
    context-path: /nacos
    namespace: demo
    group: demo
    data-id: application-dev.yml
    type: yaml
    auto-refresh: true
    remote-first: true
    server-addr: 127.0.0.1:8848
    username: nacos
    password: nacos

将 application-prod.yml 文件内容修改为:

nacos:
  config:
    bootstrap:
      enable: true
      log-enable: true
    context-path: /nacos
    namespace: demo
    group: demo
    data-id: application-prod.yml
    type: yaml
    auto-refresh: true
    remote-first: true
    server-addr: 127.0.0.1:8848
    username: nacos
    password: nacos

到这里基本已经实现远端配置了,不过没有实现远程刷新配置,实时生效。

2.3. 实时刷新

比如我在 nacos 上 demo 命名空间下的 application-dev.yml 中添加了一条自定义配置:

custom:
  str: 这是测试环境

在我的 demo 程序中分别使用 Spring 提供的 @Value 注解 和 Nacos 提供的 @NacosValue 注解去获取该属性值:

@Value("${custom.str}")
private String string1;

@NacosValue(value = "${custom.str}", autoRefreshed = true)
private String string2;

以 dev 环境启动项目,都可以获取到值这是测试环境,但是在我手动修改 nacos 中的配置为以下内容时:

custom:
  str: 这是测试环境(已修改)

此时不重启项目,则 string1 的值依然为这是测试环境,而 string2 的值已经自动刷新为这是测试环境(已修改)

3. 注册中心

最近开发了一个 SpringBoot 项目,需要将其发布为一个微服务,注册到 Nacos,参考 Nacos 官网文档的说明没有搞定,各种问题,最后还是使用了 SpringCloud 的依赖才成功的,下面介绍下 SpringBoot 注册到 Nacos 的过程。

如果想要不使用 SpringCloud 依赖直接将 SpringBoot 项目注册到 Nacos,可以参考这篇文章:

SpringBoot使用Nacos进行服务注册发现与配置管理

3.1. 环境介绍

当前使用的 Nacos 版本为 2.0.2,三个实例,集群部署。

本来使用的 SpringBoot 版本为 2.6.2,为了使用 Nacos,降到了 2.3.4.RELEASE。因为 SpringBoot 2.4.0 版本之后删掉了ConfigurationBeanFactoryMetadata,而 Nacos 需要用到这个,所以会报如下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nacosConfigurationPropertiesBinder': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata

我的 SpringBoot 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>

或者使用2.4.0版本之前的最新版本2.3.12.RELEASE

在这里插入图片描述

3.2. 配置过程

一个普通的 SpringBoot 项目,首先需要在 pom.xml 中添加依赖:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.2.3.RELEASE</version>
</dependency>

项目启动类上需要添加注解:

import org.springframework.cloud.client.discovery.EnableDiscoveryClient
...
@EnableDiscoveryClient

接下来需要修改配置文件,添加下面三项配置:

#服务名
spring.application.name=output-server-test

#Nacos服务地址
spring.cloud.nacos.discovery.server-addr=192.168.0.10:30000

#Nacos命名空间,注意要和网关服务gateway在同一个命名空间下
spring.cloud.nacos.discovery.namespace=gtcom-console

项目启动成功后,就可以在 Nacos 的服务管理中的服务列表中的对应命名空间下看到注册成功的服务了。

3.3. 网关配置

想要让其他服务通过网关能成功调用该服务,还需要在网关服务的配置文件中添加对应的路由,比如我这个项目的所有接口地址前缀是/output

server.servlet.context-path=/output

这时需要在网关服务的配置文件中添加:

spring:
  cloud:
    gateway:
      routes:
      #输出服务
      - id: output-server-test
        uri: lb://output-server-test
        predicates: 
          - Path=/output/**