/// <summary> /// 实例化SessionCache /// </summary> /// <param name="cache"></param> public SessionCache(ICacheStrategy cache) { this.cache = cache; this.queue = new Queue <QueueTimeSpan>(); ThreadPool.QueueUserWorkItem(SaveCache); }
/// <summary> /// 构造函数 /// </summary> private ShopCache() { if (MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) { applyMemCached = true; } if (applyMemCached) { cs = new MemCachedStrategy(); } else { cs = new DefaultCacheStrategy(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); //LogVisitor clv = new CacheLogVisitor(); //cs.Accept(clv); cacheConfigTimer.AutoReset = true; cacheConfigTimer.Enabled = true; cacheConfigTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed); cacheConfigTimer.Start(); } }
/// <summary> /// 加载缓存策略 /// </summary> public static void Load() { try { TargetStrategyInfo TargetStrategy = StrategyManage.GetTargetStrategy("Cache"); string TargetStrategyFilePath = SuperManager.FileFullPath("~/Strategy/" + TargetStrategy.StrategyFile); Assembly _Assembly = Assembly.LoadFile(TargetStrategyFilePath); if (_Assembly.IsHasAttributeClass<StrategyCodeAttribute>()) { string StrategyDomainName = TargetStrategy.StrategyFile.RemoveEndChar(".dll"); string StrategyClassFullName = StrategyDomainName + "." + TargetStrategy.ClassName; Assembly asmb = Assembly.LoadFrom(TargetStrategyFilePath); var AttributeType = asmb.GetType(StrategyClassFullName); _CacheStrategy = (ICacheStrategy)Activator.CreateInstance(AttributeType); } else { string StrategyDirectory = SuperManager.FileFullPath("~/Strategy/"); string[] StrategyFileNameList = Directory.GetFiles(System.Web.HttpRuntime.BinDirectory, "*.Strategy.*.dll", SearchOption.TopDirectoryOnly); } } catch (Exception ex) { ex.ToLog(); } }
/// <summary> /// 构造函数 /// </summary> private DNTCache() { if (MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) applyMemCached = true; if (RedisConfigs.GetConfig() != null && RedisConfigs.GetConfig().ApplyRedis) applyRedis = true; if (applyMemCached || applyRedis) { try { cs = cachedStrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType("Discuz.EntLib." + (applyMemCached ? "MemCachedStrategy" : "RedisStrategy") + ", Discuz.EntLib", false, true)); } catch { throw new Exception("请检查Discuz.EntLib.dll文件是否被放置在bin目录下并配置正确"); } } else { cs = new DefaultCacheStrategy(); if (rootXml.HasChildNodes) rootXml.RemoveAll(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); } }
/// <summary> /// 构造函数 /// </summary> private DNTCache() { if(MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) applyMemCached = true; if (applyMemCached) { try { cs = memcachedStrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType("Discuz.EntLib.MemCachedStrategy, Discuz.EntLib", false, true)); } catch { throw new Exception("请检查Discuz.EntLib.dll文件是否被放置在bin目录下并配置正确"); } } else { cs = new DefaultCacheStrategy(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); cacheConfigTimer.AutoReset = true; cacheConfigTimer.Enabled = true; cacheConfigTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed); cacheConfigTimer.Start(); } }
/// <summary> /// Constructs a new instance of the execution plan /// </summary> public CacheExecutionPlan(ICache cache, ICacheExceptionHandler exceptionHandler, ICacheStrategy <T> cacheStrategy) { _cache = cache; _exceptionHandler = exceptionHandler; _cacheStrategy = cacheStrategy; _cacheStrategyAsync = cacheStrategy as ICacheStrategyAsync <T>; }
/// <summary> /// 加载默认的缓存策略 /// </summary> public void LoadDefaultCacheStrategy() { lock (lockHelper) { cs = new DefaultCacheStrategy(); } }
/// <summary> /// 构造函数 /// </summary> private DNTCache() { if (MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) { applyMemCached = true; } if (RedisConfigs.GetConfig() != null && RedisConfigs.GetConfig().ApplyRedis) { applyRedis = true; } if (applyMemCached || applyRedis) { try { cs = cachedStrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType("Discuz.EntLib." + (applyMemCached ? "MemCachedStrategy" : "RedisStrategy") + ", Discuz.EntLib", false, true)); } catch { throw new Exception("请检查Discuz.EntLib.dll文件是否被放置在bin目录下并配置正确"); } } else { cs = new DefaultCacheStrategy(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); } }
/// <summary> /// 构造函数 /// </summary> private CacheProvider() { //if (MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) // applyMemCached = true; //if (RedisConfigs.GetConfig() != null && RedisConfigs.GetConfig().ApplyRedis) // applyRedis = true; if (applyMemCached || applyRedis) { try { cs = cachedStrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType("MemCache.EntLib." + (applyMemCached ? "MemCachedStrategy" : "RedisStrategy") + ", MemCache.EntLib", false, true)); } catch { throw new Exception("请检查MemCache.EntLib.dll文件是否被放置在bin目录下并配置正确"); } } else { cs = new DefaultCacheStrategy(); if (rootXml.HasChildNodes) { rootXml.RemoveAll(); } objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); } }
/// <summary> /// 加载指定的缓存策略 /// </summary> /// <param name="ics"></param> public void LoadCacheStrategy(ICacheStrategy ics) { lock (lockHelper) { cs = ics; } }
public static ICacheStrategy CreateCacheStrategy() { if (_cacheStrategy == null) _cacheStrategy = new MemcachedStrategy(); return _cacheStrategy; }
/// <summary> /// 构造函数 /// </summary> private CysoftCache() { //TODO:YZQ 临时禁用 //if (MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) // applyMemCached = true; //if (RedisConfigs.GetConfig() != null && RedisConfigs.GetConfig().ApplyRedis) // applyRedis = true; if (applyMemCached || applyRedis) { try { string typeName = string.Format("Cysoft.CacheStrategy.{0}, Cysoft.CacheStrategy", (applyMemCached ? "MemCached" : "Redis")); cs = cachedStrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType(typeName: typeName, throwOnError: false, ignoreCase: true)); } catch { throw new Exception("请检查Cysoft.CacheStrategy.dll文件是否被放置在bin目录下并配置正确"); } } else { cs = new DefaultCacheStrategy(); if (rootXml.HasChildNodes) { rootXml.RemoveAll(); } objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); } }
/// <summary> /// 功能:静态构造函数,创建默认的缓存实例 /// </summary> static CacheHelper() { try { //获取缓存策略类别 string strCacheStrategyType = ConfigurationManager.AppSettings["CacheStrategyType"]; if (!string.IsNullOrWhiteSpace(strCacheStrategyType)) { //获取缓存过期时间 string strCacheExpiration = ConfigurationManager.AppSettings["CacheExpiration"]; double value; if (!string.IsNullOrWhiteSpace(strCacheExpiration)) { double.TryParse(strCacheExpiration, out value); s_cacheExpiration = TimeSpan.FromMinutes(value); } //创建缓存策略类实例 var redisConfigInfo = JsonConfigInfo.LoadFromFile("cache.json"); s_cacheStrategy = ComponentLoader.Load <ICacheStrategy>(redisConfigInfo); } } catch (Exception ex) { string strMessage = SysLogHelper.GetErrorLogInfo(ex, true); SysLogHelper.LogMessage("CacheHelper.Static", strMessage, LogLevel.Error); } }
public CachedMeasurementRepository( SensateContext context, IGeoQueryService geo, ILogger <MeasurementRepository> logger, ICacheStrategy <string> cache) : base(context, geo, logger) { this._cache = cache; }
/// <summary> /// 加载默认的缓存策略 /// </summary> public void LoadDefaultCacheStrategy() { lock (LockHelper) { //当使用MemCached或redis时 _cs = new DefaultCacheStrategy(); } }
public AppStateManager(IEnumerable <IAppHost> appHosts, IVirtualPathProvider virtualPathProvider, ICacheStrategy cacheStrategy, IAppDomainManager appDomainManager) { _virtualPathProvider = virtualPathProvider; _appHosts = appHosts; _cacheStrategy = cacheStrategy; _appDomainManager = appDomainManager; }
/// <summary> /// 构造函数 /// </summary> private BaseCache() { cs = new DefaultCacheStrategy(); if (rootXml.HasChildNodes) rootXml.RemoveAll(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); }
/// <summary> /// Initializes a new instance of the <see cref="WebChatSettingsFromApi" /> class. /// </summary> /// <param name="apiUrl">The API URL.</param> /// <param name="proxyProvider">The proxy provider.</param> /// <param name="cache">The cache.</param> /// <exception cref="System.ArgumentNullException">apiUrl</exception> public WebChatSettingsFromApi(Uri apiUrl, IProxyProvider proxyProvider, ICacheStrategy <WebChatSettings> cache) { if (apiUrl == null) { throw new ArgumentNullException(nameof(apiUrl)); } _apiUrl = apiUrl; _proxyProvider = proxyProvider; _cache = cache; }
/// <summary> /// 构造函数 /// </summary> private SASCache() { cs = new DefaultCacheStrategy(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); //LogVisitor clv = new CacheLogVisitor(); //cs.Accept(clv); }
/// <summary> /// 选择为redis缓存时,请指定操作哪个数据库 /// </summary> /// <param name="cacheType"></param> /// <param name="dbNum"></param> public CacheContext(CacheTypeEnum cacheType, int dbNum = -1) { if (cacheType == CacheTypeEnum.LocalCache) { this.strategy = new LocalCacheStrategy(); } else { this.strategy = new RedisStrategy(dbNum); } }
/// <summary> /// 获取缓存数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> internal static T GetCache <T>(this ICacheStrategy cache, string key) { if (cache == null) { return(CacheHelper.Get <T>(key)); } else { return(cache.GetObject <T>(key)); } }
/// <summary> /// 移除缓存数据 /// </summary> /// <param name="key"></param> internal static void RemoveCache(this ICacheStrategy cache, string key) { if (cache == null) { CacheHelper.Remove(key); } else { cache.RemoveObject(key); } }
/// <summary> /// 加载指定的缓存策略,实现策略的动态更新 /// </summary> /// <param name="ics">要更换的缓存策略</param> public static void LoadCacheStrategy(ICacheStrategy ics) { lock (lockHelper) { //当不使用MemCached时 if (!applyMemCached) { cs = ics; } } }
/// <summary> /// 插入缓存数据 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="seconds"></param> internal static void InsertCache(this ICacheStrategy cache, string key, object value, int seconds) { if (cache == null) { CacheHelper.Insert(key, value, seconds); } else { cache.AddObject(key, value, TimeSpan.FromSeconds(seconds)); } }
/// <summary> /// 构造函数 /// </summary> private SuHuiCache() { _cs = new DefaultCacheStrategy(); if (RootXml.HasChildNodes) { RootXml.RemoveAll(); } _objectXmlMap = RootXml.CreateElement("Cache"); //建立内部XML文档. RootXml.AppendChild(_objectXmlMap); }
/// <summary> /// Initializes a new instance of the <see cref="WebChatSettingsFromApi" /> class. /// </summary> /// <param name="apiSettings">Settings for the API.</param> /// <param name="httpClientProvider">Strategy to get the HttpClient instance used for requests.</param> /// <param name="cache">The cache.</param> /// <exception cref="System.ArgumentNullException">apiUrl</exception> public WebChatSettingsFromApi(IOptions <WebChatApiSettings> apiSettings, IHttpClientProvider httpClientProvider, ICacheStrategy <WebChatSettings> cache) { if (apiSettings == null || apiSettings.Value == null) { throw new ArgumentNullException(nameof(apiSettings)); } _apiUrl = apiSettings.Value.WebChatSettingsUrl; _httpClientProvider = httpClientProvider ?? throw new ArgumentNullException(nameof(httpClientProvider)); _cache = cache; _cache.CacheDuration = TimeSpan.FromDays(apiSettings.Value.CacheMinutes); }
/// <summary> /// 构造函数 /// </summary> private DNTCache() { if (MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) { applyMemCached = true; } if (RedisConfigs.GetConfig() != null && RedisConfigs.GetConfig().ApplyRedis) { applyRedis = true; } if (LLServerConfigs.GetConfig() != null && LLServerConfigs.GetConfig().ApplyLLServer) { applyLLServer = true; } if (applyMemCached || applyRedis || applyLLServer) { try { string cacheStratetyName; if (applyMemCached) { cacheStratetyName = "MemCachedStrategy"; } else if (applyRedis) { cacheStratetyName = "RedisStrategy"; } else { cacheStratetyName = "LLStrategy"; } cs = cachedStrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType("Discuz.EntLib." + cacheStratetyName + ", Discuz.EntLib", false, true)); } catch { throw new Exception("请检查Discuz.EntLib.dll文件是否被放置在bin目录下并配置正确"); } } else { cs = new DefaultCacheStrategy(); if (rootXml.HasChildNodes) { rootXml.RemoveAll(); } objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); } }
/// <summary> /// 构造函数 /// </summary> private WbCache() { cs = new DefaultCacheStrategy(); if (rootXml.HasChildNodes) { rootXml.RemoveAll(); } objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); }
/// <summary> /// 设置本地缓存超时时间 /// </summary> /// <param name="timeout">超时时间,单位:秒</param> public void SetLocalCacheTimeout(int timeout) { if (timeout > 0) { this.localCache = CacheFactory.Create("Local_" + base.bucketName, CacheType.Local); this.localCache.Timeout = timeout; this.localTimeSpan = TimeSpan.FromSeconds(timeout); } else { this.localCache = null; } }
/// <summary> /// 加载缓存策略 /// </summary> private static void Load() { try { string[] fileNameList = Directory.GetFiles(System.Web.HttpRuntime.BinDirectory, "BonSite.CacheStrategy.*.dll", SearchOption.TopDirectoryOnly); _cachestrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType(string.Format("BonSite.CacheStrategy.{0}.CacheStrategy, BonSite.CacheStrategy.{0}", fileNameList[0].Substring(fileNameList[0].IndexOf("CacheStrategy.") + 14).Replace(".dll", "")), false, true)); } catch { throw new BSException("创建\"缓存策略对象\"失败,可能存在的原因:未将\"缓存策略程序集\"添加到bin目录中;将多个\"缓存策略程序集\"添加到bin目录中;\"缓存策略程序集\"文件名不符合\"BonSite.CacheStrategy.{策略名称}.dll\"格式"); } }
public DashboardController(IUserRepository users, ISensorStatisticsRepository stats, ISensorRepository sensors, IUserTokenRepository tokens, IAuditLogRepository logs, ICacheStrategy <string> cache, IHttpContextAccessor ctx) : base(users, ctx) { this._stats = stats; this._sensors = sensors; this._logs = logs; this._tokens = tokens; this.m_cache = cache; }
/// <summary> /// 加载默认的缓存策略,实现策略的默认还原 /// </summary> public static void LoadDefaultCacheStrategy() { lock (lockHelper) { //当不使用MemCached时 if (applyMemCached) { cs = memcachedStrategy; } else { cs = new DefaultCacheStrategy(); } } }
/// <summary> /// 构造函数 /// </summary> private DNTCache() { cs = new DefaultCacheStrategy(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); //LogVisitor clv = new CacheLogVisitor(); //cs.Accept(clv); cacheConfigTimer.AutoReset = true; cacheConfigTimer.Enabled = true; cacheConfigTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed); cacheConfigTimer.Start(); }
private static object _locker = new object(); //锁对象 #endregion Fields #region Constructors static BSPCache() { try { string[] fileNameList = Directory.GetFiles(System.Web.HttpRuntime.BinDirectory, "BrnShop.CacheStrategy.*.dll", SearchOption.TopDirectoryOnly); _icachestrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType(string.Format("BrnShop.CacheStrategy.{0}.CacheStrategy, BrnShop.CacheStrategy.{0}", fileNameList[0].Substring(fileNameList[0].IndexOf("CacheStrategy.") + 14).Replace(".dll", "")), false, true)); } catch { throw new BSPException("创建'缓存策略对象'失败,可能存在的原因:未将'缓存策略程序集'添加到bin目录中;'缓存策略程序集'文件名不符合'BrnShop.CacheStrategy.{策略名称}.dll'格式"); } _icachemanager = new CacheByRegex(); }
/// <summary> /// 加载默认的缓存策略 /// </summary> public void LoadDefaultCacheStrategy() { lock (lockHelper) { //当使用MemCached或redis时 if (applyMemCached || applyRedis) { cs = cachedStrategy; } else { cs = new DefaultCacheStrategy(); } } }
private static ICacheManager _icachemanager = null; //缓存管理 static BSPCache() { try { string[] fileNameList = Directory.GetFiles(System.Web.HttpRuntime.BinDirectory, "BrnShop.CacheStrategy.*.dll", SearchOption.TopDirectoryOnly); _icachestrategy = (ICacheStrategy)Activator.CreateInstance(Type.GetType(string.Format("BrnShop.CacheStrategy.{0}.CacheStrategy, BrnShop.CacheStrategy.{0}", fileNameList[0].Substring(fileNameList[0].IndexOf("CacheStrategy.") + 14).Replace(".dll", "")), false, true)); } catch { throw new BSPException("创建'缓存策略对象'失败,可能存在的原因:未将'缓存策略程序集'添加到bin目录中;'缓存策略程序集'文件名不符合'BrnShop.CacheStrategy.{策略名称}.dll'格式"); } _icachemanager = new CacheByRegex(); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceInvocationHandler"/> class. /// </summary> /// <param name="config"></param> /// <param name="container"></param> /// <param name="service"></param> /// <param name="serviceType"></param> /// <param name="cache"></param> public ServiceInvocationHandler(CastleFactoryConfiguration config, IServiceContainer container, IService service, Type serviceType, ICacheStrategy cache, IServiceLog logger) { this.config = config; this.container = container; this.serviceType = serviceType; this.service = service; this.cache = cache; this.logger = logger; this.hostName = DnsHelper.GetHostName(); this.ipAddress = DnsHelper.GetIPAddress(); this.cacheTimes = new Dictionary<string, int>(); var methods = CoreHelper.GetMethodsFromType(serviceType); foreach (var method in methods) { var contract = CoreHelper.GetMemberAttribute<OperationContractAttribute>(method); if (contract != null && contract.CacheTime > 0) cacheTimes[method.ToString()] = contract.CacheTime; } }
/// <summary> /// 构造函数 /// </summary> private ShopCache() { if (MemCachedConfigs.GetConfig() != null && MemCachedConfigs.GetConfig().ApplyMemCached) applyMemCached = true; if (applyMemCached) cs = new MemCachedStrategy(); else { cs = new DefaultCacheStrategy(); objectXmlMap = rootXml.CreateElement("Cache"); //建立内部XML文档. rootXml.AppendChild(objectXmlMap); //LogVisitor clv = new CacheLogVisitor(); //cs.Accept(clv); cacheConfigTimer.AutoReset = true; cacheConfigTimer.Enabled = true; cacheConfigTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed); cacheConfigTimer.Start(); } }
private CacheStrategyFactory() { string cacheStrategy = CacheConfig.CacheStrategy; if (cacheStrategy.ToLower() == "memcached") { if (!string.IsNullOrEmpty(CacheConfig.MemcacheServerList)) { string[] memcacheServerList = CacheConfig.MemcacheServerList.Split(','); MemCacheHelper.SetServerList("WKT_CacheServer",memcacheServerList); cachedStrategy = new MemCacheStrategy(); } else { // 如果没有设置memcache server则采用默认的缓存机制 cachedStrategy = new DefaultCacheStrategy(); } } else if (cacheStrategy.ToLower() == "entlib") { cachedStrategy = new DefaultCacheStrategy(); } }
/// <summary> /// 加载默认的缓存策略 /// </summary> public void LoadDefaultCacheStrategy() { lock (lockHelper) { //当使用MemCached或redis时 if (applyMemCached || applyRedis || applyLLServer) { cs = cachedStrategy; } else { cs = new DefaultCacheStrategy(); } } }
/// <summary> /// Set the custom cache strategy <see cref="ICacheStrategy" /> /// </summary> /// <param name="cacheStrategy"></param> internal void SetCacheStrategy(ICacheStrategy cacheStrategy) { _cacheStrategy = cacheStrategy; }
/// <summary> /// Caches a file from the web using the GET method. /// </summary> /// <param name="url">The url to request.</param> /// <param name="cachePath">The path where the cached file will be saved.</param> /// <param name="cacheStrategy">decides file cache state and duration</param> /// <param name="action">A validation or processing action to be run after downloading the file but before copying it to <paramref name="cachePath"/>.</param> public static CacheResult CacheFile(string url, string cachePath, ICacheStrategy cacheStrategy, PostDownloadAction action) { return CacheFileInternal(HttpMethod.Get, url, cachePath, cacheStrategy, null, action); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceInvocationHandler"/> class. /// </summary> /// <param name="config"></param> /// <param name="container"></param> /// <param name="service"></param> /// <param name="serviceType"></param> /// <param name="cache"></param> public LocalInvocationHandler(CastleFactoryConfiguration config, IServiceContainer container, IService service, Type serviceType, ICacheStrategy cache, IServiceLog logger) : base(config, container, service, serviceType, cache, logger) { this.container = container; //TO DO }
public void LoadDefaultCacheStrategy() { lock (lockHelper) { cs = new DefaultCacheStrategy(); } }
/// <summary> /// Set the custom cache strategy <see cref="ICacheStrategy" /> /// </summary> /// <param name="cacheStrategy"></param> public void SetCacheStrategy(ICacheStrategy cacheStrategy) { _cacheStrategy = cacheStrategy; }
/// <summary> /// 加载默认的缓存策略 /// </summary> public void LoadDefaultCacheStrategy() { lock (lockHelper) { //当不使用MemCached时 if (applyMemCached) { cs = memcachedStrategy; } else { cs = new DefaultCacheStrategy(); } } }
/// <summary> /// 加载指定的缓存策略 /// </summary> /// <param name="ics"></param> public void LoadCacheStrategy(ICacheStrategy ics) { lock (lockHelper) { //当不使用MemCached时 //if (!applyMemCached) //{ cs = ics; //} } }
/// <summary> /// ��ʼ������ /// </summary> /// <returns></returns> private static ICacheStrategy Init() { return icachestrategy = new DefaultCacheStrategy(); }
public AtMqCache() { cache = GetCacheStrategy(); }
/// <summary> /// Caches a file from the web using the POST method. /// </summary> /// <param name="url">The url to request.</param> /// <param name="cachePath">The path where the cached file will be saved.</param> /// <param name="cacheStrategy">decides file cache state and duration</param> /// <param name="parameters">The POST parameters.</param> /// <param name="action">A validation or processing action to be run after downloading the file but before copying it to <paramref name="cachePath"/>.</param> public static CacheResult CacheFilePost(string url, string cachePath, ICacheStrategy cacheStrategy, IEnumerable<KeyValuePair<string, string>> parameters, PostDownloadAction action) { return CacheFileInternal(HttpMethod.Post, url, cachePath, cacheStrategy, parameters, action); }
/// <summary> /// Caches a file from the internets. /// </summary> /// <param name="method">specifies GET or POST</param> /// <param name="url">the url to request</param> /// <param name="cachePath">the path where the cached file will be saved</param> /// <param name="cacheStrategy">decides file cache state and duration</param> /// <param name="parameters">parameters for POST requests</param> /// <param name="action">a validation or processing action to be run after downloading the file but before copying it to <paramref name="cachePath"/></param> private static CacheResult CacheFileInternal(HttpMethod method, string url, string cachePath, ICacheStrategy cacheStrategy, IEnumerable<KeyValuePair<string, string>> parameters, PostDownloadAction action) { CacheResult currentResult; string tempPath = null; // validate parameters if (method == HttpMethod.Get && parameters != null) throw new ArgumentException("GET method and parameters don't mix"); // check whether the file is cached currentResult = IsFileCached(cachePath, cacheStrategy); if (currentResult.State == CacheState.Cached) return currentResult; try { // download to a temp file switch (method) { case HttpMethod.Get: tempPath = DownloadUrlGet(url); break; case HttpMethod.Post: tempPath = DownloadUrlPost(url, parameters); break; default: throw new ArgumentException("Unknown HTTP method " + method.ToString()); } // call the PostDownloadAction if there is one if (action != null) action(tempPath); // we assume the file is fine if the PostDownloadAction didn't throw an exception File.Copy(tempPath, cachePath, true); // return success return new CacheResult(cachePath, true, CacheState.Cached, cacheStrategy.GetCachedUntil(cachePath)); } catch (Exception ex) { // if we currently have a valid local copy of the file, even if out of date, return that info if (currentResult.State != CacheState.Uncached) return CacheResult.FromExisting(currentResult, ex); else return CacheResult.Uncached(ex); } finally { // get rid of the temp file, don't care if it doesn't work try { if (!string.IsNullOrEmpty(tempPath)) File.Delete(tempPath); } catch { /* pass */ } } }
public void LoadCacheStrategy(ICacheStrategy ics) { lock (lockHelper) { cs = ics; } }
/// <summary> /// Checks whether a file exists and is fresh. /// </summary> /// <param name="path">the path to the cached file</param> /// <param name="cacheStrategy">decides cache state and duration</param> /// <returns></returns> public static CacheResult IsFileCached(string path, ICacheStrategy cacheStrategy) { try { FileInfo info = new FileInfo(path); DateTime cachedUntil; if (info.Exists) { cachedUntil = cacheStrategy.GetCachedUntil(path); if (DateTime.Now < cachedUntil) return new CacheResult(path, false, CacheState.Cached, cachedUntil); else return new CacheResult(path, false, CacheState.CachedOutOfDate, cachedUntil); } else { return CacheResult.Uncached(path); } } catch (Exception ex) { return CacheResult.Uncached(path, ex); } }
/// <summary> /// Set the Ioc factory to use /// </summary> /// <param name="logFactory">Log factory to use</param> public static void SetCurrent(ICacheStrategy cacheStrategy) { _currentCacheStrategy = cacheStrategy; }