SpringBoot2集成nacos(一)

SpringBoot集成Nacos配置详解
本文详细解析了SpringBoot项目中集成Nacos配置管理的常见问题及解决方法,包括必须配置的参数、NacosConfigUtils源码分析、正确配置type属性及启用预加载配置的必要条件。

根据nacos官网的描述,集成时总是出现错误,读不到nacos中的配置,用的nacos-config-spring-boot-starter版本为0.2.3。
 

后来经过debug,发现有几个参数是必须配置的,否则项目不会启动成功。


    public NacosPropertySource reqNacosConfig(Properties configProperties, String dataId, String groupId, ConfigType type) {
        String config = NacosUtils.getContent(builder.apply(configProperties), dataId, groupId);
        NacosPropertySource nacosPropertySource = new NacosPropertySource(dataId, groupId,
                buildDefaultPropertySourceName(dataId, groupId, configProperties), config, type.getType());
        nacosPropertySource.setDataId(dataId);
        nacosPropertySource.setType(type.getType());
        nacosPropertySource.setGroupId(groupId);
        return nacosPropertySource;
    }

上边是nacos的NacosConfigUtils源码片段,

                buildDefaultPropertySourceName(dataId, groupId, configProperties), config, type.getType());

 

上边的type是在nacos中配置的内容格式,

/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0  = the "License"");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.nacos.api.config;

/**
 * @author liaochuntao
 * @date 2019-06-14 21:12
 **/
public enum ConfigType {

    /**
     * config type is "properties"
     */
    PROPERTIES("properties"),

    /**
     * config type is "xml"
     */
    XML("xml"),

    /**
     * config type is "json"
     */
    JSON("json"),

    /**
     * config type is "text"
     */
    TEXT("text"),

    /**
     * config type is "html"
     */
    HTML("html"),

    /**
     * config type is "yaml"
     */
    YAML("yaml");

    String type;

    ConfigType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
}

 

单独在nacos中指定类型,在运行时还是会报空指针异常,因此还需要在配置nacos时指定:nacos.config.type

另外还需要配置的是nacos.config bootstrap.enable=true或nacos.config bootstrap.log.enable=true,这两个配置必须指定其一。因为在NacosConfigApplicationContextInitializer的initialize方法中会调用enable()方法中判断这两个配置项是否其一为true。

public class NacosConfigApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

  

@Override
    public void initialize(ConfigurableApplicationContext context) {
        CacheableEventPublishingNacosServiceFactory singleton = CacheableEventPublishingNacosServiceFactory.getSingleton();
        singleton.setApplicationContext(context);
        environment = context.getEnvironment();
        if (!enable()) {
            logger.info("[Nacos Config Boot] : The preload configuration is not enabled");
        } else {
            Function<Properties, ConfigService> builder = properties -> {
                try {
                    return singleton.createConfigService(properties);
                } catch (
                        NacosException e) {
                    throw new RuntimeException("ConfigService can't be created with properties : " + properties, e);
                }
            };
            nacosConfigProperties = NacosConfigPropertiesUtils.buildNacosConfigProperties(environment);
            NacosConfigUtils configUtils = new NacosConfigUtils(nacosConfigProperties, environment, builder);

            if (processor.enable(environment)) {
                configUtils.addListenerIfAutoRefreshed(processor.getDeferPropertySources());
            } else {
                configUtils.loadConfig(false);
                configUtils.addListenerIfAutoRefreshed();
            }

        }

    }


//其他代码省略...
    
private boolean enable() {
        return processor.enable(environment) || Boolean.parseBoolean(environment.getProperty(NacosConfigConstants.NACOS_BOOTSTRAP, "false"));
    }

}

 SpringBoot2集成nacos的完整配置文件如下:

nacos:
  config:
    type: yaml
    server-addr: 192.168.111.111:8848
    namespace: 32a9fc67-5fc9-47a7-947b-863364d93a88
    context-path: nacos
    data-id: the-dataid
    auto-refresh: true
    group: the-group
    bootstrap:
      enable: true
      log:
        enable: true

 

### Spring Boot 3.4 集成 Nacos 服务发现和配置管理教程 #### 添加依赖项 为了使Spring Boot应用程序能够利用Nacos的服务发现功能,在`pom.xml`文件中加入如下依赖: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> ``` 此操作允许应用注册到Nacos服务器并从中获取其他微服务的位置信息[^1]。 对于配置管理的支持,则需另外添加个特定于Nacos Config的Maven依赖来实现动态刷新配置的能力: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> ``` 这使得可以从远程Nacos实例加载配置属性,并支持热更新而无需重启服务。 #### 启动类注解修改 为了让Spring Cloud Alibaba自动装配生效,确保主程序启动类上已标注有@EnableDiscoveryClient或@SpringCloudApplication这样的注释之。这样可以激活服务发现特性以及让当前的应用成为Eureka客户端的部分(尽管这里使用的是Nacos作为实际的服务注册中心)。如果采用@SpringCloudApplication的话, 它内部已经包含了@SpringBootApplication,@EnableDiscoveryClient等功能: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } // 或者更简洁的方式: //@SpringBootApplication //@EnableDiscoveryClient 可替换为 @SpringCloudApplication ``` #### 应用配置调整 最后步是在项目的application.properties或者application.yml里指定必要的连接参数以便能成功接入Nacos集群。下面是个简单的YAML格式的例子说明如何设置这些选项: ```yaml spring: application: name: example-service # 设置服务名称用于注册表和服务间调用识别 cloud: nacos: discovery: server-addr: localhost:8848 # 指定nacos地址 config: server-addr: ${spring.cloud.nacos.discovery.server-addr} # 使用相同的server address简化维护 file-extension: yaml # 如果您希望从Nacos读取YAML格式的数据源则应如此设定 ``` 通过上述步骤完成之后,您的Spring Boot项目就已经集成Nacos的服务发现机制与外部化配置管理能力了。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值