Beispiel #1
0
        /// <summary>
        /// 刷新本地配置值
        /// </summary>
        /// <param name="metadata">配置项信息</param>
        internal static void ReloadConfigItem(ConfigMetadataApiResult metadata)
        {
            if (metadata == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(metadata.UpdateTime))
            {
                try
                {
                    ConfigMetadataApiResult result = _disconfWebApi.GetConfigMetadata(metadata.Name);
                    if (result != null)
                    {
                        metadata.UpdateTime = result.UpdateTime;
                    }
                }
                catch (Exception ex)
                {
                    LogManager.GetLogger().Warn(string.Format("获取配置项元数据信息时出现异常!配置项:{0},AppId:{1},Evn:{2},Version:{3}", metadata.Name, DisconfClientSettings.AppId, DisconfClientSettings.Environment, DisconfClientSettings.Version), ex);
                }
            }
            try
            {
                ConfigStorageItem configStorageItem = null;
                if (ConfigStorage.ContainsKey(metadata.Name))
                {
                    configStorageItem = ConfigStorage[metadata.Name];
                }

                ConfigStorageItem newConfigStorageItem = CreateConfigStorageItem(metadata.Name, metadata.Type, metadata.UpdateTime);

                if (configStorageItem == null)
                {
                    configStorageItem = newConfigStorageItem;
                }
                else
                {
                    configStorageItem.Data           = newConfigStorageItem.Data;
                    configStorageItem.Version        = newConfigStorageItem.Version;
                    configStorageItem.LastUpdateTime = DateTime.Now;
                }
                ConfigStorage[metadata.Name] = configStorageItem;
                configStorageItem.Callback();
                _disconfServerIsActive = true;
                SaveLocalConfig();
                LogManager.GetLogger().Info(string.Format("刷新本地配置项,{0}", JsonConvert.SerializeObject(configStorageItem)));
            }
            catch (Exception ex)
            {
                _disconfServerIsActive = false;
                LogManager.GetLogger().Error(string.Format("刷新本地配置值时出现异常!配置项:{0},AppId:{1},Evn:{2},Version:{3}", metadata.Name, DisconfClientSettings.AppId, DisconfClientSettings.Environment, DisconfClientSettings.Version), ex);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 创建本地存储配置项
        /// </summary>
        /// <param name="name">配置项名称</param>
        /// <param name="disconfNodeType">配置项类型</param>
        /// <param name="version">版本号(对应配置中的中的配置项的最后一次更新时间值)</param>
        /// <param name="data">配置项值</param>
        /// <returns></returns>
        private static ConfigStorageItem CreateConfigStorageItem(string name, DisconfNodeType disconfNodeType, string version, string data = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(data))
            {
                if (disconfNodeType == DisconfNodeType.File)
                {
                    data = _disconfWebApi.GetConfigFileContent(name);
                }
                else
                {
                    data = _disconfWebApi.GetConfigItemContent(name);
                }
            }
            ConfigStorageItem configStorageItem = new ConfigStorageItem
            {
                Name           = name,
                Data           = data,
                Version        = version,
                LastUpdateTime = DateTime.Now
            };

            if (!DisconfClientSettings.DisableZooKeeper)
            {
                ThreadPool.QueueUserWorkItem((obj) =>
                {
                    try
                    {
                        WatcherManager watcherManager = new WatcherManager(_zooKeeperClient);
                        watcherManager.WatchPath(name, data, disconfNodeType);
                    }
                    catch (Exception ex)
                    {
                        LogManager.GetLogger()
                        .Error(
                            string.Format(
                                "DisconfClient.ConfigStorageManager.CreateConfigStorageItem.WatchPath,Exception:{0}",
                                ex));
                    }
                });
            }

            return(configStorageItem);
        }
Beispiel #3
0
        public static T GetConfigValue <T>(string key, T defalut = default(T))
        {
            ConfigStorageItem item = ConfigStorageManager.GetConfigStorageItem(key);

            if (item == null)
            {
                return(defalut);
            }
            if (typeof(T) == typeof(string))
            {
                return((T)((object)item.Data));
            }

            IDataConverter dataConverter = DataConverterManager.GetDataConverter(key);

            if (dataConverter == null)
            {
                if (key.EndsWith(".json"))
                {
                    dataConverter = new JsonDataConverter();
                }
                else if (key.EndsWith(".config"))
                {
                    dataConverter = new AppSettingsDataConverter();
                }
                else if (key.EndsWith(".properties"))
                {
                    dataConverter = new PropertiesDataConverter();
                }
                else
                {
                    dataConverter = new DefalutDataConverter();
                }
            }
            return((T)dataConverter.Parse(typeof(T), item.Data));
        }
Beispiel #4
0
        /// <summary>
        /// 定时比较本地配置与配置中心配置的版本值
        /// </summary>
        private static void MonitorDisconfItemVersion()
        {
            try
            {
                IList <ConfigMetadataApiResult> changedList = new List <ConfigMetadataApiResult>();

                IList <ConfigMetadataApiResult> list = _disconfWebApi.GetConfigMetadatas();
                if (list == null || list.Count <= 0)
                {
                    return;
                }
                foreach (ConfigMetadataApiResult item in list)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    if (!ConfigStorage.ContainsKey(item.Name))
                    {
                        ConfigStorageItem configStorageItem = CreateConfigStorageItem(item.Name, item.Type, item.UpdateTime);
                        if (!ConfigStorage.ContainsKey(configStorageItem.Name))
                        {
                            ConfigStorage.Add(configStorageItem.Name, configStorageItem);
                            changedList.Add(item);
                        }
                    }
                    else
                    {
                        ConfigStorageItem configStorageItem = ConfigStorage[item.Name];
                        if (configStorageItem != null && configStorageItem.Version != item.UpdateTime)
                        {
                            changedList.Add(item);
                            LogManager.GetLogger().Info(string.Format("ChangeItem:{0},Version_Old:{1},Version_New:{2}", item.Name, configStorageItem.Version, item.UpdateTime));
                        }
                    }
                }
                StringBuilder sbChanged = new StringBuilder();
                foreach (ConfigMetadataApiResult item in changedList)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    ReloadConfigItem(item);
                    sbChanged.Append(item.Name).Append(" , ");
                }
                if (!DisconfClientSettings.DisableZooKeeper)
                {
                    _zooKeeperClient.MonitorZooKeeperState();
                }

                LogManager.GetLogger().Info(string.Format("DisconfClient.ConfigStorageManager.MonitorDisconfItemVersion,changed:{0}.items:{1}", changedList.Count, sbChanged));
            }
            catch (Exception ex)
            {
                try
                {
                    _disconfServerIsActive = false;
                    LogManager.GetLogger().Error("定时比较本地配置与配置中心配置的版本值时出现异常!", ex);
                }
                catch
                {
                    // ignored
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// 从配置中心加载该应用下的全部配置信息
        /// </summary>
        private static void LoadConfigItemsFromServer()
        {
            IList <ConfigMetadataApiResult> list = _disconfWebApi.GetConfigMetadatas();

            if (list == null || list.Count <= 0)
            {
                throw new Exception(string.Format("配置中心没有为应用:{0}配置过任何配置项!", DisconfClientSettings.AppId));
            }

            //获取所有文件类型的配置信息
            IList <Task> tasks = new List <Task>();

            foreach (ConfigMetadataApiResult item in list)
            {
                if (item == null || item.Type == DisconfNodeType.Item)
                {
                    continue;
                }
                ConfigMetadataApiResult configMetadata = item;
                Task task = Task.Factory.StartNew(() =>
                {
                    ConfigStorageItem configStorageItem = CreateConfigStorageItem(configMetadata.Name, configMetadata.Type, configMetadata.UpdateTime);
                    if (!ConfigStorage.ContainsKey(configStorageItem.Name))
                    {
                        ConfigStorage.Add(configStorageItem.Name, configStorageItem);
                    }
                });
                tasks.Add(task);
            }
            //获取所有配置项类型的配置信息
            Task task1 = Task.Factory.StartNew(() =>
            {
                IList <ConfigItemContentApiResult> items = _disconfWebApi.GetAllConfigItemContent();
                if (items != null)
                {
                    foreach (ConfigItemContentApiResult item in items)
                    {
                        if (item == null)
                        {
                            continue;
                        }
                        ConfigStorageItem configStorageItem = null;
                        if (ConfigStorage.ContainsKey(item.Name))
                        {
                            configStorageItem = ConfigStorage[item.Name];
                        }
                        if (configStorageItem == null)
                        {
                            string name = item.Name;
                            ConfigMetadataApiResult apiResult = list.FirstOrDefault(m => m.Name == name);
                            string version = null;
                            if (apiResult != null)
                            {
                                version = apiResult.UpdateTime;
                            }
                            configStorageItem = CreateConfigStorageItem(item.Name, DisconfNodeType.Item, version, item.Value);
                        }
                        else
                        {
                            configStorageItem.Data = item.Value;
                        }

                        ConfigStorage[configStorageItem.Name] = configStorageItem;
                    }
                }
            });

            tasks.Add(task1);
            Task.WaitAll(tasks.ToArray());
            SaveLocalConfig();
            _disconfServerIsActive = true;
        }
Beispiel #6
0
        /// <summary>
        /// 设置配置类的映射关系
        /// </summary>
        /// <param name="configClassType">配置类的类型</param>
        /// <param name="configPropertyInfo">配置属性的信息</param>
        /// <param name="disconfAttribute">配置特性</param>
        private static void SetConfigClassMapper(Type configClassType, PropertyInfo configPropertyInfo, DisconfAttribute disconfAttribute)
        {
            if (disconfAttribute == null)
            {
                throw new ArgumentNullException("disconfAttribute");
            }
            if (string.IsNullOrWhiteSpace(disconfAttribute.Name))
            {
                throw new ArgumentNullException("disconfAttribute.Name");
            }

            if (!ConfigStorage.ContainsKey(disconfAttribute.Name))
            {
                throw new Exception(string.Format("配置中心未配置名为:{0}的配置项!", disconfAttribute.Name));
            }

            //将一些常用的配置文件的扩展名匹配到指定的数据转换器
            Type dataConverterType = disconfAttribute.DataConverterType;

            if (dataConverterType == null)
            {
                if (disconfAttribute.Name.EndsWith(".json"))
                {
                    dataConverterType = typeof(JsonDataConverter);
                }
                else if (disconfAttribute.Name.EndsWith(".config"))
                {
                    dataConverterType = typeof(AppSettingsDataConverter);
                }
                else if (disconfAttribute.Name.EndsWith(".properties"))
                {
                    dataConverterType = typeof(PropertiesDataConverter);
                }
                else
                {
                    dataConverterType = typeof(DefalutDataConverter);
                }
            }

            //根据配置类的类型或配置属性的类型注册对应的数据转换器
            IDataConverter dataConverter = (IDataConverter)Activator.CreateInstance(dataConverterType, true);
            Type           registerType  = configPropertyInfo == null ? configClassType : configPropertyInfo.PropertyType;

            DataConverterManager.RegisterDataConverter(registerType, dataConverter);


            ConfigStorageItem item   = ConfigStorage[disconfAttribute.Name];
            ConfigClassMapper mapper = new ConfigClassMapper
            {
                //DisconfNodeType = disconfAttribute.DisconfNodeType,
                ConfigPropertyInfo = configPropertyInfo,
                ConfigClassType    = configClassType
            };

            item.ConfigClassMapper = mapper;
            item.RefreshConfigObject();
            if (disconfAttribute.CallbackType != null)
            {
                ICallback callback = (ICallback)Activator.CreateInstance(disconfAttribute.CallbackType, true);
                ConfigCallbackManager.RegisterCallback(disconfAttribute.Name, callback);
                item.ConfigClassMapper.ConfigNodeName = disconfAttribute.Name;
            }
            ConfigStorage[item.Name] = item;
        }