All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.javaclub.configcenter.spring.config.ConfigFactory Maven / Gradle / Ivy

The newest version!
/*
 * @(#)ConfigFactory.java	2017年6月9日
 *
 * Copyright (c) 2017. All Rights Reserved.
 *
 */

package com.github.javaclub.configcenter.spring.config;


import static com.github.javaclub.configcenter.client.util.Utils.classForName;
import static com.github.javaclub.configcenter.client.util.Utils.enumToMap;
import static com.github.javaclub.configcenter.client.util.Utils.isBlank;
import static com.github.javaclub.configcenter.client.util.Utils.isEmptyArray;
import static com.github.javaclub.configcenter.client.util.Utils.isNotBlank;
import static com.github.javaclub.configcenter.client.util.Utils.split;
import static com.github.javaclub.configcenter.client.util.Utils.splitByFirstSeparator;
import static com.github.javaclub.configcenter.client.util.Utils.startsWithIgnoreCase;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.github.javaclub.configcenter.client.ConfigCenterClient;
import com.github.javaclub.configcenter.client.ConfigChangeListener;
import com.github.javaclub.configcenter.client.DefaultConfigCenterClient;
import com.github.javaclub.configcenter.client.conf.LocalConfigserverConf;
import com.github.javaclub.configcenter.client.domain.ConfigChangedEvent;
import com.github.javaclub.configcenter.client.domain.ValueWrapper;
import com.google.common.collect.Maps;

/**
 * ConfigFactory 从配置中心读取并监听需要的配置信息
 *
 * @author Gerald Chen
 * @version $Id: ConfigFactory.java 2017年6月9日 9:32:51 Exp $
 */
public class ConfigFactory extends ConcurrentHashMap implements InitializingBean {

	private static final long serialVersionUID = 1L;
	
	static final Logger log = LoggerFactory.getLogger(ConfigFactory.class);
	
	/**
	 * 配置项枚举常量类型 
	 */
	private String configEnumClass;
	
	private Integer appId;
	private String appKey;
	
	/**
	 * key:配置项key value:配置项描述说明 
	 */
	private Map configKeys;
	
	public String getConfigEnumClass() {
		return configEnumClass;
	}

	public void setConfigEnumClass(String configEnumClass) {
		this.configEnumClass = configEnumClass;
	}

	/**
	 * 取配置项的原生字符串值
	 *
	 * @param configKey 配置项key
	 * @return configValue of configKey
	 */
	public String getConfigValue(String configKey) {
		return this.get(configKey);
	}
	
	/**
	 * 直接获取配置为bean对象,配置项值为JSON格式
	 *
	 * @param configKey 配置项key
	 * @param clazz The type of bean
	 * @return
	 */
	public  T getConfigAsBean(String configKey, Class clazz) {
		String text = this.getConfigValue(configKey);
		if(isNotBlank(text)) {
			return JSONObject.parseObject(text, clazz);
		}
		return null;
	}
	
	public Map getConfigAsWrappedValueMap(String configKey) {
		Map map = Maps.newHashMap();
		String text = this.getConfigValue(configKey);
		if(isBlank(text)) {
			return map;
		}
		String[] lines = split(text, "\n");
		if(null == lines || 0 >= lines.length) {
			return map;
		}
		for (String line : lines) {
			if(isBlank(line) || startsWithIgnoreCase(line, "#"))  {
				continue;
			}
			String[] pair = splitByFirstSeparator(line, "=");
			if(isEmptyArray(pair) || 2 != pair.length) {
				continue;
			}
			if(isBlank(pair[0]) || null == pair[1]) {
				continue;
			}
			map.put(pair[0].trim(), ValueWrapper.create(null != pair[1] ? pair[1].trim() : pair[1]));
		}
		return map;
	}
	
	public Map getConfigAsPropertyMap(String configKey) {
		Map map = Maps.newHashMap();
		String text = this.getConfigValue(configKey);
		if(isBlank(text)) {
			return map;
		}
		String[] lines = split(text, "\n");
		if(isEmptyArray(lines)) {
			return map;
		}
		for (String line : lines) {
			if(isBlank(line) || startsWithIgnoreCase(line, "#"))  {
				continue;
			}
			String[] pair = splitByFirstSeparator(line, "=");
			if(isEmptyArray(pair) || 2 != pair.length) {
				continue;
			}
			map.put(pair[0], null != pair[1] ? pair[1].trim() : pair[1]);
		}
		return map;
	}
	
	/**
	 * 更新配置项的值
	 *
	 * @param configKey 配置项key
	 * @param newValue  配置项新值
	 */
	public void updateConfigValue(String configKey, String newValue) {
		ConfigCenterClient client = DefaultConfigCenterClient.getInstance();
		client.setConfig(appId, appKey, configKey, newValue);
	}
	
	/**
	 * 拿到所有已经配置订阅的配置项key
	 *
	 * @return java.util.Set that type is String
	 */
	public Set getInterestedKeys() {
		Set keys = new HashSet<>();
		if(!CollectionUtils.isEmpty(configKeys)) {
			keys = getConfigKeys().keySet();
		}
		return keys;
	}
	

	@Override
	public void afterPropertiesSet() throws Exception {
		this.loadKeysByEnumClassIfNecessary();
		if (null == appId || 0 >= appId || isBlank(appKey)) {
			appId = LocalConfigserverConf.getInstance().getAppId();
			appKey = LocalConfigserverConf.getInstance().getAppKey();
		}
		ConfigCenterClient client = DefaultConfigCenterClient.getInstance(); // 环境参数必须一致
		Set keys = this.getInterestedKeys();
		for (final String key : keys) {
			String value = client.getConfig(appId, appKey, key, new ConfigChangeListener() {
				@Override
				public void onChange(ConfigChangedEvent event) {
					put(key, event.getNewConfigValue());
					log.warn("ConfigCenter update key={}\t newValue={}", key,  event.getNewConfigValue());
				}
			});
			if (null != value) {
				this.put(key, value.trim());
			}
			log.warn("Init configValue key={}\t value={}", key, value);
		}
	}
	
	public Integer getAppId() {
		return appId;
	}

	public void setAppId(Integer appId) {
		this.appId = appId;
	}

	public String getAppKey() {
		return appKey;
	}

	public void setAppKey(String appKey) {
		this.appKey = appKey;
	}

	public Map getConfigKeys() {
		return configKeys;
	}

	public void setConfigKeys(Map configKeys) {
		this.configKeys = configKeys;
	}
	
	/**
	 * 从枚举类型中加载配置项的key
	 */
	void loadKeysByEnumClassIfNecessary() throws Exception {
		if (isBlank(configEnumClass)) {
			return;
		}
		Class clazz = classForName(getConfigEnumClass());
		Map map = enumToMap(clazz, new String[] { "getKey", "getDescription" });
		Map managedKeys = Maps.newHashMap(); // 已经显示配置注入的key
		for (Map.Entry e : map.entrySet()) {
			managedKeys.put(e.getKey().toString(), e.getValue());
		}
		if(managedKeys.size() > 0) {
			this.setConfigKeys(managedKeys);
		}
	}
	

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy