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

com.github.javaclub.configcenter.client.ConfigLocalSave Maven / Gradle / Ivy

The newest version!
package com.github.javaclub.configcenter.client;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.github.javaclub.configcenter.client.domain.CfgVO;
import com.github.javaclub.configcenter.client.util.DESCoder;
import com.github.javaclub.configcenter.client.util.LocalFileUtils;
import com.github.javaclub.toolbox.ToolBox.Collections;
import com.github.javaclub.toolbox.ToolBox.Files;
import com.github.javaclub.toolbox.ToolBox.Maps;
import com.github.javaclub.toolbox.ToolBox.Strings;
import com.google.common.collect.Lists;

/**
 * 本地保存一份配置,容灾
 */
public class ConfigLocalSave {
	
	private static final Logger logger = LoggerFactory.getLogger(ConfigLocalSave.class);
	private static ConfigLocalSave instance = new ConfigLocalSave();
	
	public static ConfigLocalSave getInstance() {
		return instance;
	}
	
	public synchronized Map get(int appid, String appkey, String configkey) {
		try {
			List> cfgList = readConfigFromFile(appid, appkey);
			if (Collections.isNotEmpty(cfgList)) {
				for (Map cfg : cfgList) {
					if (Strings.equals(cfg.get("key"), configkey)) {
						return cfg;
					}
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return null;
	}

	public synchronized boolean save(int appid, String appkey, String configkey, String configValue, long timestamp) {
		try {
			List> cfgList = readConfigFromFile(appid, appkey);
			List writeStr = new ArrayList();
			if (cfgList != null) {
				boolean exists = false;
				// 先遍历对已经存在的key 进行 => 更新
				for (Map cfg : cfgList) {
					if (cfg.get("key").equals(configkey)) {  // 更新旧配置
						exists = true;
						cfg.put("key", configkey);
						cfg.put("value", configValue);
						cfg.put("timestamp", String.valueOf(timestamp));
					}
					String str = JSONObject.toJSONString(cfg);
					if (!writeStr.contains(str)) {
						writeStr.add(str);
					}
				}
				if (!exists) {
					Map cfg = new TreeMap();
					cfg.put("key", configkey);
					cfg.put("value", configValue);
					cfg.put("timestamp", String.valueOf(timestamp));
					writeStr.add(JSONObject.toJSONString(cfg));
				}
			} else {
				Map cfg = new TreeMap();
				cfg.put("key", configkey);
				cfg.put("value", configValue);
				cfg.put("timestamp", String.valueOf(timestamp));
				writeStr.add(JSONObject.toJSONString(cfg));
			}
			FileUtils.writeLines(getConfigDataFile(appid), writeStr, false);
			return true;
		} catch (Exception e) {
			logger.error("", e);
		}
		return false;
	}
	
	public synchronized boolean snapshot(int appid, String appkey, Collection cfgList) {
		try {
			if (Collections.isEmpty(cfgList)) {
				return false;
			}
			List writeStr = new ArrayList();
			for (CfgVO cfgVO: cfgList) {
				Map cfg = new TreeMap();
				cfg.put("key", cfgVO.getConfigkey());
				cfg.put("value", cfgVO.getConfigvalue());
				cfg.put("timestamp", cfgVO.getTimestamp());
				String str = JSONObject.toJSONString(cfg);
				if (!writeStr.contains(str)) {
					writeStr.add(DESCoder.encrypt(str, appkey));
				}
			}
			File localcache = getConfigDataFile(appid);
			FileUtils.writeLines(localcache, "UTF-8", writeStr, false);
			if (logger.isDebugEnabled()) {
				logger.debug("ConfigLocalCache was saved: configKeyCount={} localcache={}", writeStr.size(), localcache.getAbsolutePath());
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return false;
	}
	
	public synchronized boolean snapshotsAppConfigKeys(int appId, String content) {
		if (Strings.isNotBlank(content)) {
			try {
				File localfile = getConfigKeysFile(appId);
				List lines = Lists.newArrayList(content.trim());
				FileUtils.writeLines(localfile, "UTF-8", lines, false);
				return true;
			} catch (IOException e) {
				logger.error("snapshotsAppConfigKeys error, appId=" + appId, e);
			}
		}
		return false;
	}
	
	public synchronized String readLocalAppConfigKeys(int appId) {
		try {
			File file = getConfigKeysFile(appId);
			return Files.readAsString(file, "UTF-8");
		} catch (Exception e) {
			logger.error("readLocalAppConfigKeys error, appId=" + appId, e);
		}
		return Strings.EMPTY;
	}

	public List> readConfigFromFile(int appid, String appkey) throws Exception {
		List cfgList = FileUtils.readLines(getConfigDataFile(appid), "utf-8");
		if (cfgList != null && !cfgList.isEmpty()) {
			List> list = new ArrayList>();
			for (String cfg : cfgList) {
				list.add(asTreeMap(cfg, appkey));
			}
			return list;
		}
		return null;
	}
	
	private File getConfigKeysFile(int appid) throws IOException {
		String filePath = Strings.concat(LocalFileUtils.getLocalSaveDirPath(), 
				"/", appid, "_keys_", getEnv());
		File f = new File(filePath);
		if (!f.exists()) {
			f.createNewFile();
		}
		return f;
	}
	
	private File getConfigDataFile(int appid) throws IOException {
		String filePath = Strings.concat(LocalFileUtils.getLocalSaveDirPath(), 
				"/", appid, "_", getEnv());
		File f = new File(filePath);
		if (!f.exists()) {
			f.createNewFile();
		}
		return f;
	}
	
	String getEnv() {
		return DefaultConfigCenterClient.getInstance().getEnv();
	}
	
	@SuppressWarnings("unchecked")
	Map asTreeMap(String cfg, String appkey) throws Exception {
		Map map = JSONObject.parseObject(DESCoder.decrpty(cfg, appkey), Map.class);
		return Maps.newTreeMap(map);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy