Nacos配置Json格式

本文介绍了如何在SpringBoot应用中使用Nacos作为配置中心,并实现对`testReportConf`配置项的实时监听,以及如何将接收到的JSON配置映射为NaCosJsonData对象。
摘要由CSDN通过智能技术生成

1、项目设置允许读取Json格式

@NacosPropertySource(dataId = "testReportConf", groupId = CommonConstant.PROJECT_NAME, autoRefreshed = true, type = ConfigType.JSON)


@NacosPropertySource(dataId = "application", groupId = "groupId", autoRefreshed = true)
@NacosPropertySource(dataId = "testReportConf", groupId = "groupId", autoRefreshed = true, type = ConfigType.JSON)
@EnableScheduling
@ComponentScan({"com.xm.autotestplatform", "com.xm"})
@SpringBootApplication
public class AutoTestPlatformApplication {

    public static void main(String[] args) {
        SpringApplication.run(AutoTestPlatformApplication.class, args);
    }

}

2、编写一个监听器用于监听Nacos配置的更改



import com.alibaba.boot.nacos.config.properties.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.google.gson.Gson;
import com.xm.autotestplatform.config.nacos.NaCosJsonData;
import com.xm.autotestplatform.config.nacos.NacosHelper;
import com.xm.autotestplatform.utils.ThreadPoolFactory;
import com.xm.constants.CommonConstant;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Properties;
import java.util.concurrent.Executor;



@Component
@Slf4j
@Data
public class TestReportConfListenerAgent implements InitializingBean {
    @Resource
    private NacosConfigProperties nacosConfigProperties;
    public   ConfigService configService;

    @Override
    public void afterPropertiesSet() {
        configService = getConfigService();
        this.listener();

    }
    public void listener() {
        Listener listener = new Listener() {
            @Override
            public Executor getExecutor() {
                return ThreadPoolFactory.getCommonPoll();
            }
            @SneakyThrows
            @Override
            public void receiveConfigInfo(String configInfo) {
                log.info("configInfo:{}", configInfo);
                String jsonConfig = configService.getConfig("testReportConf", "autotestplatform", 3000);
                Gson gson = new Gson();
                NaCosJsonData naCosJsonData = gson.fromJson(jsonConfig, NaCosJsonData.class);
                NacosHelper.setNaCosJsonData(naCosJsonData);
            }
        };
        try {
            // 监听
            configService.addListener("testReportConf", nacosConfigProperties.getGroup(), listener);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }


    public void publishConfig(String msg) {
        try {
            configService.publishConfig(CommonConstant.AGENT_LOG_DATAID,nacosConfigProperties.getGroup(),msg);
            configService.publishConfig("testReportConf",nacosConfigProperties.getGroup(),msg);
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取ConfigService
     *
     * @return
     */
    public ConfigService getConfigService() {
        String serverAddr = nacosConfigProperties.getServerAddr();
        String nameSpace = nacosConfigProperties.getNamespace();
        String username = nacosConfigProperties.getUsername();
        String password = nacosConfigProperties.getPassword();
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.put(PropertyKeyConst.NAMESPACE, nameSpace);
        properties.put(PropertyKeyConst.USERNAME, username);
        properties.put(PropertyKeyConst.PASSWORD, password);
        ConfigService configService = null;
        try {
            configService = NacosFactory.createConfigService(properties);
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return configService;
    }
}

3、上面 NacosHelper类如下 (作用是:监听器监听到值改变时唯一实例同步改变)


import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
2024/3/21 下午1:52
 **/
@Component
public class NacosHelper {
    @Resource
    private NaCosJsonData nacosJsonData;

    private static NaCosJsonData staticNaCosJsonData;

    @PostConstruct
    public void init() {
        staticNaCosJsonData = nacosJsonData;
    }


    public static void setNaCosJsonData(NaCosJsonData naCosJsonData) {
        NacosHelper.staticNaCosJsonData = naCosJsonData;
    }

    public static NaCosJsonData getNaCosJsonData() {
        return staticNaCosJsonData;
    }


}

4、将页面上配置的Json值映射成对象(加注解 @ConfigurationProperties)

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;


@Component
@ConfigurationProperties
@Data
public class NaCosJsonData {

    private ExampleConfig example;
    private String userName;

    @Data
    public static class ExampleConfig {
        private String message;
        private String timestamp;
        private List<DataItem> arrayListName; // 映射data数组

    }

}
package com.xm.autotestplatform.config.nacos;

import lombok.Data;

@Data
public class DataItem {
    private String name;
    private String value;
}
页面配置的Json值下图

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Nacos支持多层json配置的解析,可以通过以下步骤进行解析: 1.首先,从Nacos获取配置。假设我们的配置项名为config.json,获取到的配置内容为: ``` { "person": { "name": "张三", "age": 18, "gender": "男" }, "address": { "province": "江苏省", "city": "苏州市", "district": "工业园区", "street": "星湖街328号" } } ``` 2.使用json解析工具将配置内容解析为json对象。例如,使用Java中的JSONObject类: ``` String configContent = "从Nacos获取到的配置内容"; JSONObject configJson = new JSONObject(configContent); ``` 3.通过json对象获取需要的配置项值。例如,获取person节点下的name属性值: ``` String name = configJson.getJSONObject("person").getString("name"); ``` 4.如果需要获取多层嵌套的属性值,可以继续使用getJSONObject方法获取下一层的json对象。例如,获取address节点下的street属性值: ``` String street = configJson.getJSONObject("address").getString("street"); ``` 5.如果配置项中包含数组或者嵌套的数组,可以使用JSONArray类进行解析。例如,假设我们的配置项名为config.json,获取到的配置内容为: ``` { "persons": [ { "name": "张三", "age": 18, "gender": "男" }, { "name": "李四", "age": 20, "gender": "女" } ] } ``` 我们可以通过以下代码获取persons数组中第一个元素的name属性值: ``` JSONArray persons = configJson.getJSONArray("persons"); String name = persons.getJSONObject(0).getString("name"); ``` 以上就是解析Nacos多层json配置的基本步骤。需要根据实际情况进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值