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

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

The newest version!
/*
 * @(#)DefaultAppServerConfig.java	2021-8-21
 *
 * Copyright (c) 2021. All Rights Reserved.
 *
 */

package com.github.javaclub.configcenter.client;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.javaclub.configcenter.ConfigServerConstants.Client;
import com.github.javaclub.configcenter.client.conf.LocalConfigserverConf;
import com.github.javaclub.configcenter.client.domain.ConfigKeysIncrEvent;
import com.github.javaclub.configcenter.client.util.DESCoder;
import com.github.javaclub.configcenter.client.util.Utils;
import com.github.javaclub.configcenter.spring.utils.SpringInjector;
import com.github.javaclub.toolbox.AppBootHook;
import com.github.javaclub.toolbox.ToolBox.Strings;
import com.github.javaclub.toolbox.conf.ConfigcenterLoader;
import com.github.javaclub.toolbox.thread.ExecutorServiceInstance;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;

/**
 * DefaultAppServerConfig
 *
 * @author Gerald Chen
 * @version $Id: DefaultAppServerConfig.java 2021-8-21 0:45:54 Exp $
 */
public class DefaultAppServerConfig implements AppConfig {

	private static final Logger logger = LoggerFactory.getLogger(DefaultAppServerConfig.class);

	private static class ServerConfigHolder {
		private static DefaultAppServerConfig INSTANCE = new DefaultAppServerConfig();
	}

	private static volatile boolean inited = false;
	private static volatile List defaultAppConfigKeys = new CopyOnWriteArrayList();

	private int appId;
	private String appKey;
	
	private AtomicInteger counter;
	private EventBus eventBus;

	private ScheduledExecutorService executorService;
	
	private DefaultConfigCenterClient client;
	private final LocalConfigserverConf serverConf = LocalConfigserverConf.getInstance();
	
	static final int MAX_LOG_TIMES = 1;

	private DefaultAppServerConfig() {
		client = DefaultConfigCenterClient.getInstance();
		eventBus = SpringInjector.getInstance(EventBus.class);
		counter = new AtomicInteger(0);
		
		appId = serverConf.getAppId();
		appKey = serverConf.getAppKey();
		logger.info("DefaultAppServerConfig inited: appId={}, appKey={}", appId, Strings.filter(appKey));
		
		this.executorService = ExecutorServiceInstance.get(Client.CLIENT_WORKER_KEYS_PULL);
		if (appId > 0) {
			this.initAppConfigKeys();
		}
	}


	private void initAppConfigKeys() {
		this.executorService.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				if (AppBootHook.isAppShuttingDown()) {
					return;
				}
				if (counter.get() <= MAX_LOG_TIMES && logger.isInfoEnabled()) {
					logger.info("Refresh defaultAppConfigKeys start: appId={}", appId);
				}
				pullAppConfigKeys();
			}
		}, 10L, 5000L, TimeUnit.MILLISECONDS);
	}

	public static final DefaultAppServerConfig getInstance() {
		return ServerConfigHolder.INSTANCE;
	}

	@Override
	public String getProperty(String key, String defaultValue) {
		if(!defaultAppConfigKeys.isEmpty() && !defaultAppConfigKeys.contains(key)) {
			return defaultValue;
		}
		String val = client.getConfig(appId, appKey, key, null);
		return Objects.toString(val, defaultValue);
	}

	@Override
	public String getPropertyWithListener(String configKey, ConfigChangeListener listener) {
		return client.getConfig(appId, appKey, configKey, listener);
	}
	
	@Override
	public void removeKeyWithListener(String configKey) {
		if (null != defaultAppConfigKeys && defaultAppConfigKeys.contains(configKey)) {
			defaultAppConfigKeys.remove(configKey);
		}
		client.removeConfig(appId, appKey, configKey);
	}

	@Override
	public Set getPropertyNames() {
		if(null != defaultAppConfigKeys && defaultAppConfigKeys.size() > 0) {
			return Sets.newHashSet(defaultAppConfigKeys);
		}
		return pullAppConfigKeys();
	}
	
	protected Set pullAppConfigKeys() {
		String resp = null;
		try {
			resp = client.doQueryKeys(appId);
		} catch (Exception e) {
		}
		if (!Utils.isRespOK(resp)) {
			try {
				resp = client.doQueryKeys(appId);
			} catch (Exception e) {
			}
		}
		if (logger.isInfoEnabled() && counter.get() <= MAX_LOG_TIMES) {
			logger.info("DefaultAppServerConfig#pullAppConfigKeys: appId={}, resp={}", appId, resp);
		}

		JSONObject result = JSONObject.parseObject(resp);
		if (result.getShort("code") == 0) {
			if (Utils.isNotBlank(result.getString("result"))) {
				try {
					String v = DESCoder.decrpty(result.getString("result"), appKey);
					if (Utils.isNotBlank(v)) {
						List list = JSON.parseArray(v, String.class);
						if (null != list) {
							try {
								long index = counter.incrementAndGet();
								ConfigKeysIncrEvent incrKeyEvent = new ConfigKeysIncrEvent(appId);
								for (String key : list) {
									if (!defaultAppConfigKeys.contains(key)) {
										incrKeyEvent.addIncrKey(key);
									}
								}
								defaultAppConfigKeys.clear();
								defaultAppConfigKeys.addAll(list);
								if (index > 1 && inited && incrKeyEvent.hasIncredKeys()) {
									eventBus.post(incrKeyEvent);
									if (logger.isInfoEnabled()) {
										logger.info("DefaultAppServerConfig configKeysIncr: incrKeys={}", incrKeyEvent.getIncrKeys());
									}
									incrKeyEvent.getIncrKeys().forEach(key -> {
										ConfigcenterLoader.getInstance().addMonitorKey(key);
									});
								}
								if (index > Integer.MAX_VALUE - 10000) {
									counter.set(1);
								}
								if (counter.get() <= MAX_LOG_TIMES) {
									logger.info("{} AppConfigKeys was pulled.", list.size());
								}
								return Sets.newHashSet(list);
							} finally {
								inited = true;
								if (!Utils.isLocalcached(result)) {
									result.put("localcached", true);
									final String respText = JSONObject.toJSONString(result);
									ExecutorServiceInstance.get().execute(() -> {
										ConfigLocalSave.getInstance().snapshotsAppConfigKeys(appId, respText);
									});
								}
							}
						}
					}
				} catch (Exception e) {
					logger.error("", e);
				}
			}
		}
		
		return Sets.newHashSet();
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy