likes
comments
collection
share

springboot集成nacos配置中心

作者站长头像
站长
· 阅读数 15

之前我们谈了nacos的安装及基本的配置管理相关的功能使用,本篇我们聊下如何在项目中对接nacos服务。nacos本身是包含配置中心和注册中心的功能,如果我们只把nacos作为配置中心使用,那么我们就只需要集成nacos官方提供的用于springboot应用对接nacos配置中心的sdk包。

本篇我们以springboot 2.7.0版本为例讲解集成nacos配置中心的功能。

1、修改pom文件

修改springboot应用的pom文件,添加如下依赖:

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

2、修改application.yml文件

修改springboot应用resources目录下的application.yml(或yaml或properties)文件,新增nacos相关配置,用来读取我们在3.3部分新增的配置信息

server:
  port: 8080
  servlet:
    context-path: /nacos


spring:
  application:
    name: springboot-nacos

# nacos相关配置
nacos:
  config:
    bootstrap:
      #开启系统启动时预读取nacos的配置,用于满足@Value注入数据的场景
      enable: true
    # 配置所属命名空间的id,此处我们配置名称为dev的id,可以在命名空间列表查看id的值
    namespace: f3be4de8-02ce-4ce0-9d58-8063bb9e071f
    # 配置所属分组
    group: DEFAULT_GROUP
    # 配置ID
    data-id: com.xk.nacos.springboot
    # 配置文件类型,对应nacos配置页面的配置格式,默认是properties
    type: yaml
    # nacos服务器地址
    server-addr: localhost:8848
    # 开启自动刷新nacos配置
    auto-refresh: true
    # 针对配置项同名的情况,是否允许nacos的配置覆盖本地的配置
    remote-first: true

3、编写代码验证

我们在controller层新增一个接口如下:

package com.xk.nacos.springboot.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xk
 * @since 2023.05.07 14:25
 */
@RequestMapping("/config")
@RestController
public class NacosConfigController {

    @Value(value = "${secret}")
    private String secret;
    @Value("${nacos.config.data-id}")
    private String dataId;
    @Value("${nacos.config.group}")
    private String group;

    @NacosInjected
    private ConfigService configService;

    @GetMapping("getSecret")
    public String getSecret(){
        return secret;
    }

    // 可以获取nacos同一个命名空间下的其他dataId和group下面的配置
    @GetMapping("getConfig")
    public String getConfig() throws NacosException {
        return configService.getConfig(dataId,group,5000);
    }
}

访问getSecret接口,可得到如下结果:

springboot集成nacos配置中心

nacos-getSecret

而调用getConfig接口,就能根据我们在application.yml中指定的DataId和Group获取到对应的配置。

springboot集成nacos配置中心

nacos-getConfig

经过上面两个接口的验证,我们能确定springboot应用已成功集成nacos。

4、注意事项

4.1、版本兼容问题

关于nacos-config-spring-boot-starter的版本和springboot版本的关系,nacos在官网做了如下表述:

版本 0.2.x.RELEASE对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。

但是实际使用中,可能还是会遇到问题。比如我使用springboot2.7.0版本,nacos-config-spring-boot-starter使用0.2.7版本,就会报如下错误:

Caused byorg.springframework.beans.BeanInstantiationExceptionFailed to instantiate [com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder]Constructor threw exceptionnested exception is java.lang.NoClassDefFoundErrororg/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311) ~[spring-beans-5.3.20.jar:5.3.20]
    ... 19 common frames omitted
Caused byjava.lang.NoClassDefFoundErrororg/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    at com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder.<init>(NacosBootConfigurationPropertiesBinder.java:51) ~[nacos-config-spring-boot-autoconfigure-0.2.7.jar:0.2.7]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_301]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_301]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_301]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_301]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211) ~[spring-beans-5.3.20.jar:5.3.20]
    ... 21 common frames omitted

所以实际使用时,大家还是要结合自己的情况,验证下版本上是否存在兼容问题。

结束语

觉得有收获的朋友,麻烦点击下“关注”,或者进行分享、收藏,多谢支持~

转载自:https://juejin.cn/post/7236739875532587064
评论
请登录