SpringBoot2集成nacos(一)

7 篇文章 1 订阅
5 篇文章 0 订阅

根据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

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot是一款基于Spring框架的开发工具,可以简化Java应用程序的开发过程。而Nacos是阿里巴巴开源的一款服务发现和配置管理平台。以下是关于如何在Spring Boot集成Nacos的步骤: 1. 首先,需要在Spring Boot的项目中添加Nacos的客户端依赖。可以在项目的pom.xml文件的dependencies中添加以下依赖: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> ``` 2. 在Spring Boot的配置文件application.properties中,添加Nacos的相关配置信息,包括Nacos的服务地址、应用的命名空间等。例如: ```properties spring.cloud.nacos.config.server-addr=127.0.0.1:8848 spring.cloud.nacos.config.namespace=my-namespace ``` 3. 在Spring Boot的启动类中,使用@EnableDiscoveryClient注解启用Nacos的服务发现功能。例如: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 4. 接下来,可以通过注入NacosConfigManager来读取Nacos中的配置信息。例如: ```java import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @NacosPropertySource(dataId = "example", autoRefreshed = true) public class ConfigController { @Autowired private ConfigService configService; @GetMapping("/config") public String getConfig() { String config = configService.getConfig("example", "test-group", 5000); return config; } } ``` 以上就是在Spring Boot集成Nacos的基本步骤。通过这种方式,我们可以方便地使用Nacos来管理和获取配置信息,同时也可以轻松地实现服务的注册与发现功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值