从nacos中读取自定义配置文件的两种方案

从nacos中读取自定义配置文件的两种方案1.通过配置实现 1.bootstrap配置 2.通过实现InitializingBean接口实现。

1.通过配置实现

1.bootstrap配置

从nacos中读取自定义配置文件的两种方案

从nacos中读取自定义配置文件的两种方案

从nacos中读取自定义配置文件的两种方案

2.通过实现InitializingBean接口实现

NacosConfig.java

@Configuration
public class NacosConfig {
    /** * 前提条件 要求 serverAddr、namespace、group使用bootstrap.yml 中 spring cloud nacos config 的。 * @return */
    @Bean
    public Map<String, Class> nacosConfigLocalCacheInfoMap() {
        // key:dataId, value:对应数据类型
        Map<String, Class> map = new HashMap<>();
        map.put("sumJSON", User.class); // 自定义json格式实体类映射 sumJSON为在nacos上的配置文件的dataId 具体数据为json格式数据
     	map.put("testText", String.class);
        map.put("testJson1", List.class);
        map.put("testJson2", User.class);
        map.put("testInteger", Integer.class);

        return map;
    }
}

NacosConfigInfo.java

package com.findme.demo.config;

import org.springframework.context.annotation.Configuration;

/** * nacos 配置 信息 */
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;
    /** * 获取nacos groupId * <p>默认NacosConstant.GROUP_ID</p> * * @return nacos groupId */
    private String group;
    /** * 获取nacos dataId * * @return nacos dataId */
    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;
    }
}

NacosConfigLocalCatch.java

package com.findme.demo.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 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 org.springframework.stereotype.Component;

import javax.annotation.Resource;
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;

@Component

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

    @Resource(name = "nacosConfigLocalCacheInfoMap")
    private Map<String, Class> nacosConfigLocalCacheInfoMap;
    @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();

    /** * bean初始化 触发 执行 * * @throws Exception */
    @Override
    public void afterPropertiesSet() throws Exception {
        nacosConfigLocalCacheInfoMap.forEach((k, v) -> {
            NacosConfigInfo nacosConfigInfo = new NacosConfigInfo(nacosConfigProperties.getServerAddr(),
                    nacosConfigProperties.getNamespace(), nacosConfigProperties.getGroup(),
                    k, true, nacosConfigLocalCacheInfoMap.get(k));

            this.listener(nacosConfigInfo);
        });
    }

    public void listener(NacosConfigInfo nacosConfigInfo) {
        Listener listener = new Listener() {
            /** * 监听-工作线程池 * @return */
            @Override
            public Executor getExecutor() {
                return threadPoolExecutor;
            }
            /** * 接受到Nacos 具体 配置信息变动 * * @param configInfo */
            @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);
    }

    /** * 获取ConfigService * * @return */
    private ConfigService getConfigService(NacosConfigInfo nacosConfigInfo) {
        String serverAddr = nacosConfigInfo.getServerAddr();
        String nameSpace = nacosConfigInfo.getNamespace();
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        // 设置为public后会控制台会循环打印
// 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) {
        if (cls != nacosConfigLocalCacheInfoMap.get(dataId)) {
            throw new IllegalArgumentException("类型异常");
        }

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

}

testController.java

    @Autowired
    private NacosConfigLocalCatch nacosConfigLocalCatch;
 
    @RequestMapping("/test2")
    public String test2() {
        logger.info("-------------test2---------------");
        String testText = nacosConfigLocalCatch.get("testText", String.class);
        List testJson1 = nacosConfigLocalCatch.get("testJson1", List.class);
        User testJson2 = nacosConfigLocalCatch.get("testJson2", User.class);
        Integer testInteger = nacosConfigLocalCatch.get("testInteger", Integer.class);
        return testText+" , "+testJson1+" , "+testJson2+" , "+testInteger;
    }

3.pom配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.findme</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2020.0.0</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- nacos-config -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.2.4.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR8</version>
            </dependency>
        </dependencies>
    </dependencyManagement>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

今天的文章从nacos中读取自定义配置文件的两种方案分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/19057.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注