spring读取nacos配置中心json文件

场景

数据对应关系表之前在系统是一静态代码形式存储,配置数据存储在代码中不安全,且改动配置需要重新提交部署代码,现使用nacos配置中心存储一系列数据对应关系表。

需引入nacos config包

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
package com.hints.common.config;

public class NacosConfigInfo {
    public NacosConfigInfo(String serverAddr, String namespace, String group, String dataId, boolean refresh, Class cls) {
        this.serverAddr = serverAddr;
        this.namespace = namespace;
        this.group = group;
        this.dataId = dataId;
        this.refresh = refresh;
        this.cls = cls;
    }

    public NacosConfigInfo() {
    }

    private String serverAddr;
    private String namespace;
    private String group;
    private String dataId;
    private boolean refresh = true;
    private Class cls = String.class;

    public String getServerAddr() {
        return serverAddr;
    }

    public void setServerAddr(String serverAddr) {
        this.serverAddr = serverAddr;
    }

    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public String getDataId() {
        return dataId;
    }

    public void setDataId(String dataId) {
        this.dataId = dataId;
    }

    public boolean isRefresh() {
        return refresh;
    }

    public void setRefresh(boolean refresh) {
        this.refresh = refresh;
    }

    public Class getCls() {
        return cls;
    }

    public void setCls(Class cls) {
        this.cls = cls;
    }

    public long getTimeout() {
        return 5000L;
    }
}

package com.hints.common.config;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSON;
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.hints.common.utils.Constants;
import com.hints.common.utils.spring.SpringxUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class NacosConfigLocalCatch implements InitializingBean {
    private Map<String, Object> localCatchMap = new HashMap<>();

    @Autowired
    private NacosConfigProperties nacosConfigProperties;


    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            2, 4, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<>(100),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected final String clazzSimpleName = getClass().getSimpleName();

    @Override
    public void afterPropertiesSet() throws Exception {
            NacosConfigInfo nacosConfigInfo = new NacosConfigInfo(nacosConfigProperties.getServerAddr(),
                    nacosConfigProperties.getNamespace(), nacosConfigProperties.getGroup(),
                    "domain.json", true, HashMap.class);

            this.listener(nacosConfigInfo);
    }

    public void listener(NacosConfigInfo nacosConfigInfo) {
        Listener listener = new Listener() {
            @Override
            public Executor getExecutor() {
                return threadPoolExecutor;
            }
            @Override
            public void receiveConfigInfo(String configInfo) {
                logger.info("{}#receiveConfigInfo receive configInfo. configInfo={}", clazzSimpleName, configInfo);
                compile(configInfo, nacosConfigInfo);
            }
        };
        ConfigService configService = this.getConfigService(nacosConfigInfo);
        String config = null;
        try {
            config = configService.getConfig(nacosConfigInfo.getDataId(), nacosConfigInfo.getGroup(), nacosConfigInfo.getTimeout());
            logger.info("{}#afterPropertiesSet init configInfo. configInfo={}", clazzSimpleName, config);
            // 初始化
            compile(config, nacosConfigInfo);
            // 监听
            configService.addListener(nacosConfigInfo.getDataId(), nacosConfigInfo.getGroup(), listener);
        } catch (NacosException e) {
            e.printStackTrace();
            throw new RuntimeException("nacos server 监听 异常! dataId = " + nacosConfigInfo.getDataId());
        }
    }

    private void compile(String config, NacosConfigInfo nacosConfigInfo) {
        Object initValue = JSON.parseObject(config, nacosConfigInfo.getCls());
        localCatchMap.put(nacosConfigInfo.getDataId(), initValue);
        Constants bean = SpringxUtils.getBean(Constants.class);
        //监听到nacos配置文件有变化,会重新初始化bean构造方法
        bean.Constants();
    }

    private ConfigService getConfigService(NacosConfigInfo nacosConfigInfo) {
        String serverAddr = nacosConfigInfo.getServerAddr();
        String nameSpace = nacosConfigInfo.getNamespace();
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.put(PropertyKeyConst.NAMESPACE, nameSpace);
        ConfigService configService;
        try {
            configService = NacosFactory.createConfigService(properties);
        } catch (NacosException e) {
            e.printStackTrace();
            throw new RuntimeException("Nacos config 配置 异常");
        }
        return configService;
    }

    public <T> T get(String dataId, Class<T> cls) {

        return (T) localCatchMap.get(dataId);
    }

}
package com.hints.common.utils;

import com.hints.common.config.NacosConfigLocalCatch;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
import com.hints.common.service.SysApiRoleService;
import com.hints.common.utils.spring.SpringxUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.*;

@Component
public final class Constants {

    private ArrayList<Map> usid;
    private static HashMap<String, String> compMap;
    private static HashMap<String, List<String>> compList;

    @PostConstruct
    public void Constants() {
        NacosConfigLocalCatch nacosConfigLocalCatch = SpringxUtils.getBean(NacosConfigLocalCatch.class);
        HashMap<String, List<String>> map = nacosConfigLocalCatch.get("domain.json", HashMap.class);
        compList = map;
        Map<String, List<String>> newData = map.entrySet()
                .stream()
                .flatMap(entry ->
                        entry.getValue()
                                .stream()
                                .map(value ->
                                        new AbstractMap.SimpleImmutableEntry<>(
                                                entry.getKey(),
                                                value
                                        )
                                )
                )
                .collect(
                        groupingBy(
                                Map.Entry::getValue,
                                mapping(
                                        Map.Entry::getKey,
                                        toList()
                                )
                        )
                );
        //TODO 以上stream将map平铺后对value进行分组实现 键值反转,待实现:HashMap> -> HashMap
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        newData.entrySet().forEach(entry -> {
            stringStringHashMap.put(entry.getKey(),entry.getValue().get(0));
        });
        compMap = stringStringHashMap;
    }
}

你可能感兴趣的:(spring,json,java)