Ejemplo n.º 1
0
        /// <summary>
        /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存
        /// </summary>
        /// <param name="cacheKey">缓存Key</param>
        /// <param name="path">文件路径</param>
        /// <param name="func">获取xml内容</param>
        /// <returns>配置词典</returns>
        private static object GetConfigDictionary(string cacheKey, string path, Func <string, object> func)
        {
            object      configs = new object();
            ObjectCache cache   = MemoryCache.Default;

            if (cache.Contains(cacheKey))
            {
                var cacheItem = cache.GetCacheItem(cacheKey);
                if (cacheItem != null)
                {
                    configs = cacheItem.Value;
                }
            }
            else
            {
                configs = func(path);
                CacheItemPolicy policy = new CacheItemPolicy {
                    Priority = CacheItemPriority.NotRemovable
                };
                cache.Set(cacheKey, configs, policy);
                List <string> filePaths = new List <string>()
                {
                    path
                };
                HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths);
                monitor.NotifyOnChanged((o) => {
                    cache.Remove(cacheKey);
                });
                policy.ChangeMonitors.Add(monitor);
            }
            return(configs);
        }
        /// <summary>
        /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存
        /// </summary>
        /// <returns></returns>
        public static List <ClientApplicationVersion> GetClientApplicationVersion()
        {
            List <ClientApplicationVersion> clientApplicationVersions = null;

            ObjectCache cache = MemoryCache.Default;

            if (cache.Contains(CacheKey))
            {
                clientApplicationVersions = cache.GetCacheItem(CacheKey).Value as List <ClientApplicationVersion>;
            }
            else
            {
                clientApplicationVersions = LoadClientApplicationConfigs();
                if (clientApplicationVersions.Any())
                {
                    CacheItemPolicy policy = new CacheItemPolicy()
                    {
                        Priority = CacheItemPriority.NotRemovable
                    };
                    cache.Set(CacheKey, clientApplicationVersions, policy);

                    List <string> filePaths = new List <string> {
                        ClientAppVersionConfigFile
                    };
                    HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths);
                    monitor.NotifyOnChanged(new OnChangedCallback((o) => cache.Remove(CacheKey)));

                    policy.ChangeMonitors.Add(monitor);
                }
            }

            return(clientApplicationVersions);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 添加到缓存
        /// </summary>
        /// <param name="value">被缓存的数据</param>
        /// <param name="cacheKey">缓存key</param>
        /// <param name="filePath">依赖缓存文件的绝对路径</param>
        public static void SetCache_M(this object value, string cacheKey, string dependency_filePath)
        {
            if (!File.Exists(dependency_filePath))
            {
                throw new FileNotFoundException("缓存依赖文件不存在");
            }

            ObjectCache     cache  = MemoryCache.Default;
            CacheItemPolicy policy = new CacheItemPolicy();

            //缓存优先级别
            policy.Priority = System.Runtime.Caching.CacheItemPriority.Default;

            cache.Set(cacheKey, value, policy);

            //设置监视对象
            HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string>()
            {
                dependency_filePath
            });

            //设置监视对象的回调操作
            //依赖文件发生变化 即删除缓存
            monitor.NotifyOnChanged(new OnChangedCallback(o =>
            {
                RemoveCache_M(cacheKey);
            }));
            //添加到监视器
            policy.ChangeMonitors.Add(monitor);
        }
        public GameTrackerService()
        {
            GamesDataUpdateTimer = new System.Timers.Timer(TimeSpan.FromDays(1).TotalMilliseconds)
            {
                AutoReset = true
            };
            GamesDataUpdateTimer.Elapsed += (sender, args) => GameStore.ReloadGamesFromCentralRepository();

            ProcessScannerTimer = new System.Timers.Timer(AppSettings.Instance.ProcessScanIntervalInSeconds * 1000)
            {
                AutoReset = true
            };
            ProcessScannerTimer.Elapsed += (sender, args) => { new ProcessScanner().ScanProcesses(ProcessScannerTimer); };

            UserActivityFileMonitor = new HostFileChangeMonitor(new[] { UserActivityStore.DataFilePath }.ToList());
            UserActivityFileMonitor.NotifyOnChanged((_) => { AllUserActivityCache.CancellationTokenSource.Cancel(); });

            WebAssetsFileMonitor = new HostFileChangeMonitor(WebAssets.AllAssetPaths.ToArray());
            WebAssetsFileMonitor.NotifyOnChanged((_) => { WebAssets.CancellationTokenSource.Cancel(); });

            WebHost = new WebHostBuilder()
                      .UseKestrel()
                      .UseStartup <WebHostConfiguration>()
                      .UseConfiguration(AppSettings.Instance.Configuration)
                      .UseSerilog()
                      .UseUrls(WebHostListenAddress)
                      .Build();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存
        /// </summary>
        /// <returns></returns>
        public static List <ReportTemplateFile> GetReportTemplates()
        {
            List <ReportTemplateFile> reportTemplates = null;

            ObjectCache cache = MemoryCache.Default;

            if (cache.Contains(CacheKey))
            {
                reportTemplates = cache.GetCacheItem(CacheKey).Value as List <ReportTemplateFile>;
            }
            else
            {
                reportTemplates = LoadReportTemplates();
                if (reportTemplates.Any())
                {
                    CacheItemPolicy policy = new CacheItemPolicy()
                    {
                        Priority = CacheItemPriority.NotRemovable
                    };
                    cache.Set(CacheKey, reportTemplates, policy);

                    var                   fileInfos = new DirectoryInfo(ReportTemplateFilesPath).GetFiles().ToList();
                    List <string>         filePaths = fileInfos.Select(f => f.FullName).ToList();
                    HostFileChangeMonitor monitor   = new HostFileChangeMonitor(filePaths);
                    monitor.NotifyOnChanged(new OnChangedCallback((o) => cache.Remove(CacheKey)));

                    policy.ChangeMonitors.Add(monitor);
                }
            }

            return(reportTemplates);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 从内存缓存中读取配置。若缓存中不存在,则重新从文件中读取配置,存入缓存
        /// </summary>
        /// <param name="cacheKey">缓存Key</param>
        /// <returns>配置词典</returns>
        public static Dictionary <string, string> GetConfigDictionary(string cacheKey)
        {
            Dictionary <string, string> configs = null;

            //1、获取内存缓存对象
            var cache = MemoryCache.Default;

            //2、通过Key判断缓存中是否已有词典内容(Key在存入缓存时设置)
            if (cache.Contains(cacheKey))
            {
                //3、直接从缓存中读取词典内容
                configs = cache.GetCacheItem(cacheKey).Value as Dictionary <string, string>;
            }
            else
            {
                //3、读取配置文件,组成词典对象,准备放到缓存中
                configs = GetFromXml();

                //4、检查是否读取到配置内容
                if (configs != null)
                {
                    //4、新建一个CacheItemPolicy对象,该对象用于声明配置对象在缓存中的处理策略
                    CacheItemPolicy policy = new CacheItemPolicy();

                    //5、因为配置文件一直需要读取,所以在此设置缓存优先级为不应删除
                    // 实际情况请酌情考虑,同时可以设置AbsoluteExpiration属性指定过期时间
                    policy.Priority = CacheItemPriority.NotRemovable;

                    //6、将词典内容添加到缓存,传入 缓存Key、配置对象、对象策略
                    // Set方法首先会检查Key是否在缓存中存在,如果存在,更新value,不存在则创建新的
                    // 这里先加入缓存再加监视的原因是:在缓存加入时,也会触发监视事件,会导致出错。
                    cache.Set(cacheKey, configs, policy);

                    //7、监视文件需要传入一个IList对象,所以即便只有一个文件也需要新建List对象
                    string        applicationPath = AppDomain.CurrentDomain.BaseDirectory;
                    string        configPath      = applicationPath + "MemeryCacheTest.exe.config";
                    List <string> filePaths       = new List <string>()
                    {
                        @"c:\config.xml", configPath
                    };

                    //8、新建一个文件监视器对象,添加对资源文件的监视
                    HostFileChangeMonitor monitor = new HostFileChangeMonitor(filePaths);

                    //9、调用监视器的NotifyOnChanged方法传入发生改变时的回调方法
                    monitor.NotifyOnChanged(new OnChangedCallback((o) =>
                    {
                        cache.Remove(cacheKey);
                    }
                                                                  ));

                    //10、为配置对象的缓存策略加入监视器
                    policy.ChangeMonitors.Add(monitor);
                }
            }
            return(configs);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 监视配置文件
        /// </summary>
        public static void MonitorConfigFile(EventHandler <SupportPlatformsChangedEventArgs> callbackOnConfigChangedHandler)
        {
            //使用基于文件缓存依赖的方式去监听文件  而不是使用 FileSystemWatch
            var cacheContainer = MemoryCache.Default;

            string cacheKey = "SupportPlatform-MonitorConfigFile";

            if (cacheContainer.Contains(cacheKey))
            {
                cacheContainer.Remove(cacheKey);
            }
            if (null != callbackOnConfigChangedHandler)
            {
                //如果已经存在这个缓存 表示已经加入了依赖监视 ,直接注册委托广播源即可
                OnConfigFileChanged += callbackOnConfigChangedHandler;
            }


            //缓存策略
            var policy = new CacheItemPolicy();

            //绝对过期
            policy.Priority = CacheItemPriority.NotRemovable;
            cacheContainer.Add(new CacheItem(cacheKey, DateTime.Now.ToString()), policy);

            //开启文件缓存 进行监视依赖
            HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string> {
                configFilePath
            });

            //当文件发生变更的时候 触发通知
            monitor.NotifyOnChanged((state) =>
            {
                //获取最新的配置 并触发事件
                //var lstNewConfigs = SupportPlatformLoader.LoadConfig();CurrentSupportPlatforms = lstNewConfigs
                //直接 通知订阅的事件 将内容列表清空 ,再次重新加载即可
                if (null != OnConfigFileChanged)
                {
                    OnConfigFileChanged(null, new SupportPlatformsChangedEventArgs {
                    });
                }
            });
            policy.ChangeMonitors.Add(monitor);
        }
Ejemplo n.º 8
0
        public void Add <T>(string key, string dependencyKey, T obj, TimeSpan timeSpan)
        {
            if (obj == null)
            {
                return;
            }
            var policy = new CacheItemPolicy {
                AbsoluteExpiration = DateTime.Now + timeSpan
            };

            LocalCache.Add(new CacheItem(key, obj), policy);
            HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string>()
            {
                dependencyKey
            });

            monitor.NotifyOnChanged(new OnChangedCallback((o) =>
            {
                LocalCache.Remove(key);
            }));
            policy.ChangeMonitors.Add(monitor);
        }
Ejemplo n.º 9
0
        public void Add <T>(string key, string dependencyKey, T obj)
        {
            if (obj == null)
            {
                return;
            }
            var policy = new CacheItemPolicy {
                Priority = CacheItemPriority.NotRemovable
            };

            LocalCache.Add(new CacheItem(key, obj), policy);
            HostFileChangeMonitor monitor = new HostFileChangeMonitor(new List <string>()
            {
                dependencyKey
            });

            monitor.NotifyOnChanged(new OnChangedCallback((o) =>
            {
                LocalCache.Remove(key);
            }));
            policy.ChangeMonitors.Add(monitor);
        }
Ejemplo n.º 10
0
        private bool RegisterMoniter(string key, params string[] dependentFiles)
        {
            if (this._isDisposed)
            {
                return(false);
            }
            string moniterKey = key + "|" + string.Join("|", dependentFiles);

            if (!this._monitors.ContainsKey(moniterKey))
            {
                lock (this._monitors)
                {
                    if (!this._monitors.ContainsKey(moniterKey))
                    {
                        HostFileChangeMonitor moniter = new HostFileChangeMonitor(dependentFiles);
                        moniter.NotifyOnChanged(delegate(object state)
                        {
                            try
                            {
                                this.Remove(key);
                                moniter.Dispose();
                            }
                            catch
                            {
                            }
                            finally
                            {
                                this._monitors.Remove(moniterKey);
                                this.RegisterMoniter(key, dependentFiles);
                            }
                        });
                        this._monitors.Add(moniterKey, moniter);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 11
0
 //设置监视器
 public void SetMonitor <T>(string path) where T : ConfigBase
 {
     if (!File.Exists(path))
     {
         return;
     }
     try
     {
         CacheItemPolicy policy = new CacheItemPolicy();
         //policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);
         //监视文件需要传入一个IList对象,所以即便只有一个文件也需要新建List对象
         var filePaths = new List <string>()
         {
             path
         };
         //新建一个文件监视器对象,添加对资源文件的监视
         var monitor = new HostFileChangeMonitor(filePaths);
         //调用监视器的NotifyOnChanged方法传入发生改变时的回调方法
         monitor.NotifyOnChanged(
             new OnChangedCallback(state =>
         {
             var config = this.LoadConfig <T>();
             if (config != null)
             {
                 Configs.AddOrUpdate(typeof(T), config, (tKey, existingVal) => { return(config); });
                 logger.Info("配置已更新,路径:" + path);
             }
         })
             );
         policy.ChangeMonitors.Add(monitor);
     }
     catch (Exception ex)
     {
         logger.Error(ex, "设置监视器出错,路径:" + path);
     }
 }
Ejemplo n.º 12
0
        void InitForMemoryCache(bool isPublic, string[] filenamesArg, string[] cachekeysArg, CacheDependency dependency, DateTime utcStart)
        {
            bool dispose = true;

            try {
                MemCache memCache = HttpRuntime.InternalCache as MemCache;
                _bits            = new SafeBitVector32(0);
                _utcLastModified = DateTime.MinValue;
                IList <String> files = filenamesArg;
                IList <String> keys  = cachekeysArg;
                if (dependency != null)
                {
                    ReadOnlyCollection <string> filePaths = (dependency._fileChangeMonitor != null) ? dependency._fileChangeMonitor.FilePaths : null;
                    ReadOnlyCollection <string> cacheKeys = (dependency._entryChangeMonitor != null) ? dependency._entryChangeMonitor.CacheKeys : null;
                    if (filePaths != null || filenamesArg != null)
                    {
                        if (filePaths == null)
                        {
                            files = filenamesArg;
                        }
                        else if (filenamesArg == null)
                        {
                            files = filePaths;
                        }
                        else
                        {
                            files = new List <String>(filenamesArg.Length + filePaths.Count);
                            foreach (string f in filenamesArg)
                            {
                                files.Add(f);
                            }
                            foreach (string f in filePaths)
                            {
                                files.Add(f);
                            }
                        }
                    }
                    if (cacheKeys != null || cachekeysArg != null)
                    {
                        if (cacheKeys == null)
                        {
                            keys = cachekeysArg;
                        }
                        else if (cachekeysArg == null)
                        {
                            keys = cacheKeys;
                        }
                        else
                        {
                            keys = new List <String>(cachekeysArg.Length + cacheKeys.Count);
                            foreach (string f in cachekeysArg)
                            {
                                keys.Add(f);
                            }
                            foreach (string f in cacheKeys)
                            {
                                keys.Add(f);
                            }
                        }
                    }
                }

                _fileChangeMonitor  = (files != null) ? new HostFileChangeMonitor(files) : null;
                _entryChangeMonitor = (keys != null) ? memCache.CreateCacheEntryChangeMonitor(keys, isPublic) : null;

                string uniqueId = null;

                if (_fileChangeMonitor != null)
                {
                    _utcLastModified = _fileChangeMonitor.LastModified.UtcDateTime;
                    uniqueId         = _fileChangeMonitor.UniqueId;
                    _fileChangeMonitor.NotifyOnChanged(new OnChangedCallback(OnChangedCallback));
                }
                if (_entryChangeMonitor != null)
                {
                    DateTime utcLastModified = _entryChangeMonitor.LastModified.UtcDateTime;
                    if (utcLastModified > _utcLastModified)
                    {
                        _utcLastModified = utcLastModified;
                    }
                    uniqueId += _entryChangeMonitor.UniqueId;
                    _entryChangeMonitor.NotifyOnChanged(new OnChangedCallback(OnChangedCallback));
                }

                _uniqueID = uniqueId;
#if DBG
                _isUniqueIDInitialized = true;
#endif
                // check if file has changed since the start time
                if (utcStart < DateTime.MaxValue)
                {
                    if (_utcLastModified > utcStart &&
                        !(_utcLastModified - DateTime.UtcNow > FUTURE_FILETIME_BUFFER))        // See VSWhidbey 400917
                    {
                        _bits[CHANGED] = true;
                    }
                }

                _bits[BASE_INIT] = true;
                if (dependency != null && dependency._bits[CHANGED])
                {
                    _bits[CHANGED] = true;
                }
                if (_bits[WANTS_DISPOSE] || _bits[CHANGED])
                {
                    Debug.Trace("CacheDependencyInit", "WANTS_DISPOSE or CHANGED.  InitForMemoryCache calling DisposeInternal");
                    DisposeInternal();
                }
                dispose = false;
            }
            finally {
                if (dispose)
                {
                    _bits[BASE_INIT] = true;
                    Debug.Trace("CacheDependencyInit", "\n\nERROR in CacheDependency.InitForMemoryCache, calling DisposeInternal");
                    DisposeInternal();
                }
            }
        }