web项目 获取nacos配置java 代码

1.主动监听nacos配置类
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 主动监听nacos配置类
 *
 * @param <T>
 */
public abstract class NacosAbstractListener<T> implements InitializingBean, Listener {

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

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

    @Autowired
    private NacosConfigManager nacosConfigManager;

    protected T data;

    public T getData() {
        return data;
    }

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

    /**
     * 监听-工作线程池
     *
     * @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);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ConfigService configService = nacosConfigManager.getConfigService();
        logger.info("configService : {}", configService);
        String configInfo = configService.getConfig(getDataId(), getGroupId(), getTimeout());
        logger.info("{}#afterPropertiesSet init configInfo. configInfo={}", clazzSimpleName, configInfo);
        compile(configInfo);
        configService.addListener(getDataId(), getGroupId(), this);
    }

    /**
     * 获取nacos dataId
     *
     * @return nacos dataId
     */
    protected abstract String getDataId();

    /**
     * 获取nacos groupId
     *
     * @return nacos groupId
     */
    protected String getGroupId() {
        return "DEFAULT_GROUP";
    }

    /**
     * 获取nacos 超时时间
     *
     * @return nacos 超时时间
     */
    protected long getTimeout() {
        return 3000L;
    }

    /**
     * 将输入转为数据
     *
     * @param dataStr
     */
    protected abstract void compile(String dataStr);

}

  2.获取值

mport cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.casc.dcs.xbom.common.entity.vo.workshop.ExtWorkshopConfigVO;
import com.casc.dcs.xbom.core.util.ExceptionUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class NacosWorkshopConfigJsonListener extends NacosAbstractListener<List<ExtWorkshopConfigVO>> {

    @Override
    protected String getDataId() {
        return "workshop-config";
    }

    /**
     * 获取nacos groupId
     *
     * @return nacos groupId
     */
    @Override
    protected String getGroupId() {
        return "BUSINESS_GROUP";
    }

    @Override
    protected void compile(String dataStr) {
        data = JSON.parseObject(dataStr, new TypeReference<ArrayList<ExtWorkshopConfigVO>>(){});
    }

    public List<ExtWorkshopConfigVO> getConfig() {
        List<ExtWorkshopConfigVO> workshopList = getData();
        if (CollectionUtil.isEmpty(workshopList)) {
            ExceptionUtil.newDxBusinessUnknowException("请确认配置中心workshop-config");
        }
        return workshopList;
    }

}

  3.创建实体

import lombok.Data;
import lombok.ToString;

@Data
@ToString(callSuper = true)
public class ExtWorkshopConfigVO {

    private String orgCode;  //组织代码

    private String orgName; //组织名称


}

  4.yml文件workshop-config.yml

[
	{
		"orgCode": "T01_01",
		"orgName": "T01"
	},
	{
		"orgCode": "T02_01",
		"orgName": "T02"
	},	
	{
		"orgCode": "T03_01",
		"orgName": "T03"
	},	
	{
		"orgCode": "T04_01",
		"orgName": "T04"
	},	
	{
		"orgCode": "T05_01",
		"orgName": "T05"
	},	
	{
		"orgCode": "T06_01",
		"orgName": "T06"
	},	
	{
		"orgCode": "T07_01",
		"orgName": "T07"
	},	
	{
		"orgCode": "T08_01",
		"orgName": "T08"
	}
	
]

  5.其他地方使用

List<ExtWorkshopConfigVO> config = nacosWorkshopConfigJsonListener.getConfig();

posted on 2022-12-29 10:19  AnkangWenqiang  阅读(136)  评论(0编辑  收藏  举报

导航