public CacheKeyA(TKey key) { _keyType = CacheKeyType.OriginKey; _objectKey = null; _originKey = key; _primitiveKey = null; }
public CacheKeyA(byte[] key) { _keyType = CacheKeyType.PrimitiveKey; _objectKey = null; _originKey = default; _primitiveKey = key; }
public CacheKeyA(object key) { _keyType = CacheKeyType.ObjectKey; _objectKey = key; _originKey = default; _primitiveKey = null; }
private void TrackCacheEvent(CacheKeyType type, string id, string eventName = "Miss") { _appInsights.TrackEvent($"MemoryCache {eventName}", new Dictionary <string, string> { { "Cache Entry Type", type.ToString() }, { "Cache Key", id } }); }
private ICacheManager GetCacheManager(CacheKeyType cacheKeyType) { switch (cacheKeyType) { case CacheKeyType.StateOnly: return(new StateCacheManager()); case CacheKeyType.StateAndDepth: return(new StateAndDepthCacheManager()); case CacheKeyType.StateAndPassedThroughStates: return(new StateAndPassedThroughCacheManager()); default: throw new InternalException("Code 1005 (not supported cache type)"); } }
public void Search_EngineRemebersCachedStates(CacheKeyType cacheKeyType) { var tree = new UnaryDeterministicTree(); var engine = new SearchEngine(CacheMode.ReuseCache, cacheKeyType) { SkipEvaluationForFirstNodeSingleNeighbor = false }; engine.Search(tree.RootState, 10); // This should put all the states in the cache var result = engine.Search(tree.RootState, 10); Assert.AreEqual(1, result.StateSequence.Count); Assert.IsTrue(result.FullTreeSearchedOrPruned); }
/// <summary> /// 构造函数。 /// </summary> /// <param name="ms"></param> /// <param name="fileKeyType"></param> public MemoryCacheItem(MemoryStream ms, CacheKeyType fileKeyType) : base() { if (ms == null) { throw new ArgumentNullException("ms"); } if (fileKeyType == CacheKeyType.MD5 && ms.Length > 0) { ms.Seek(0, SeekOrigin.Begin); this.ItemKey = iPower.Cryptography.HashCrypto.HashFile(ms, "md5"); } this.DataBytes = ms.ToArray(); }
/// <summary> /// query and format the value result by cache key type /// Hash、List、Set and String etc. /// they all has different format in order to modify by client /// </summary> /// <param name="key"></param> /// <param name="type"></param> /// <returns></returns> public string QueryWithType(string key, CacheKeyType type) { if (!_client.IsConnected) { return(string.Empty); } try { IDatabase database = _client.GetDatabase(); IOperator op = null; switch (type) { case CacheKeyType.None: break; case CacheKeyType.String: op = new RedisString(); break; case CacheKeyType.Hash: op = new RedisHash(); break; case CacheKeyType.List: op = new RedisList(); break; case CacheKeyType.Set: op = new RedisSet(); break; case CacheKeyType.SortedSet: op = new RedisSortedSet(); break; } if (op == null) { return(string.Empty); } else { return(op.Format(database, key)); } } catch (Exception ex) { return(string.Empty); } }
public static string ComputeCacheKey(string objectName, CacheKeyType cacheKeyType, params KeyValuePair <string, string>[] parameters) { string cacheKey = string.Empty; switch (cacheKeyType) { case CacheKeyType.BusinessCache: cacheKey = string.Format("BusinessData--method[method={0}]", objectName); if (parameters != null) { cacheKey = parameters.Aggregate(cacheKey, (current, route) => current + string.Format(":[{0},{1}]:", route.Key, route.Value)); } break; } return(cacheKey); }
public CacheResult Query(App app, string key) { var cache = Caching.CacheFactory.Create(app.Type, app.ConnectionString); CacheKeyType type = cache.Type(key); string value = cache.QueryWithType(key, type); TimeSpan? expire = cache.Expire(key); cache.Close(); CacheResult result = new CacheResult(); result.Expire = expire.HasValue ? expire.Value.TotalSeconds.ToString() : ""; result.Value = value; result.Key = key; result.Index = 0; result.Type = ((int)type).ToString(); return(result); }
public bool Set(string key, CacheKeyType type, string value, int timeToLive) { if (!_client.IsConnected) { return(false); } IDatabase database = _client.GetDatabase(); IOperator op = null; switch (type) { case CacheKeyType.None: case CacheKeyType.String: op = new RedisString(); break; case CacheKeyType.Hash: op = new RedisHash(); break; case CacheKeyType.List: op = new RedisList(); break; case CacheKeyType.Set: op = new RedisSet(); break; case CacheKeyType.SortedSet: op = new RedisSortedSet(); break; } if (op == null) { return(false); } else { return(op.Set(database, key, value, timeToLive)); } }
/// <summary> /// 构造函数。 /// </summary> /// <param name="filePath">文件路径。</param> /// <param name="loadType">加载方式。</param> /// <param name="fileKeyType">缓存键类型。</param> public FileCacheItem(string filePath, DataLoadType loadType, CacheKeyType fileKeyType) { this.FilePath = filePath; if (!File.Exists(this.FilePath)) { throw new ArgumentException(filePath + " 文件不存在!"); } this.FileLoadType = loadType; this.FileKeyType = fileKeyType; this.FileName = Path.GetFileNameWithoutExtension(this.FilePath); this.FileExtension = Path.GetExtension(this.FilePath); this.LastAccessDate = DateTime.Now; this.ItemSize = new FileInfo(this.FilePath).Length; this.ItemKey = this.FilePath; if (this.FileKeyType == CacheKeyType.MD5 || this.FileLoadType == DataLoadType.Load) { using (FileStream fstream = new FileStream(this.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (this.FileKeyType == CacheKeyType.MD5) { this.ItemKey = iPower.Cryptography.HashCrypto.HashFile(fstream, "md5"); fstream.Seek(0, SeekOrigin.Begin); } if (this.FileLoadType == DataLoadType.Load) { using (BufferBlockUtil block = new BufferBlockUtil()) { byte[] buf = new byte[1024]; int len = 0; while ((len = fstream.Read(buf, 0, buf.Length)) > 0) { block.Write(buf, 0, len); } this.FileBytes = block.ToArray(); } } fstream.Close(); } } }
/// <summary> /// In some search domains, remembering states that lead to wins, losses or draw can improve performance. /// Use this constructor to create an engine with a cache. /// Note that caching will only work if you implement Equals and GetHashValue in a meaningful way for your states. /// </summary> public SearchEngine(CacheMode cacheMode, CacheKeyType cacheKeyType) { CacheMode = cacheMode; CacheKeyType = cacheKeyType; if (cacheMode != CacheMode.NoCache && cacheKeyType == CacheKeyType.Unknown) { throw new MinMaxSearchException($"{nameof(CacheKeyType)} can't be of type {nameof(CacheKeyType.Unknown)} when using a cache."); } if (cacheMode == CacheMode.NoCache) { cacheManagerFactory = () => new NullCacheManager(); } else if (cacheMode == CacheMode.ReuseCache) { CacheManager = GetCacheManager(cacheKeyType); cacheManagerFactory = () => CacheManager; } else { cacheManagerFactory = () => GetCacheManager(cacheKeyType); } }
private static string CacheKey(CacheKeyType type, params string[] id) { return(type + ':' + string.Join(";", id.Select(x => x.ToLowerInvariant()))); }
public void Add <T>(string key, T value, DbNetParamterDirection direction, int sourceIndex, SourceType sourceType, CacheKeyType cacheKeyType) { if (dic.ContainsKey(key)) { throw new Exception(string.Format("参数名称重复,来自 参数位置:{0} 源:{1}", sourceIndex, sourceType == SourceType.FromClass?"来自类属性": sourceType == SourceType.FromArg ? "来自方法参数":"未知")); } dic.Add(key, new DbNetParamter { Name = key, Value = value, Direction = direction, SourceIndex = sourceIndex, SourceType = sourceType, CacheKeyType = cacheKeyType }); }
protected void ChangeCacheKeyAndPreferredHostForSpecifiedMethod(SoapHttpClientProtocol ws, MsnServiceType st, MsnServiceState ss, object request) { if (st == MsnServiceType.AB || st == MsnServiceType.Sharing || st == MsnServiceType.Storage) { DeltasList deltas = NSMessageHandler.ContactService.Deltas; if (deltas == null) { throw new MSNPSharpException("Deltas is null."); } string methodName = ss.MethodName; string preferredHostKey = ws.ToString() + "." + methodName; CacheKeyType keyType = (st == MsnServiceType.Storage) ? CacheKeyType.StorageServiceCacheKey : CacheKeyType.OmegaContactServiceCacheKey; string originalUrl = ws.Url; string originalHost = FetchHost(ws.Url); bool needRequest = false; lock (deltas.SyncObject) { needRequest = (deltas.CacheKeys.ContainsKey(keyType) == false || deltas.CacheKeys[keyType] == string.Empty || (deltas.CacheKeys[keyType] != string.Empty && (deltas.PreferredHosts.ContainsKey(preferredHostKey) == false || deltas.PreferredHosts[preferredHostKey] == String.Empty))); } if (needRequest) { try { Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, ws.GetType().ToString() + " is requesting a cachekey and preferred host for calling " + methodName); switch (keyType) { case CacheKeyType.OmegaContactServiceCacheKey: ws.Url = ws.Url.Replace(originalHost, MSNService.ContactServiceRedirectionHost); break; case CacheKeyType.StorageServiceCacheKey: ws.Url = ws.Url.Replace(originalHost, MSNService.StorageServiceRedirectionHost); break; } ws.GetType().InvokeMember(methodName, System.Reflection.BindingFlags.InvokeMethod, null, ws, new object[] { request }); } catch (Exception ex) { bool getHost = false; if (ex.InnerException is WebException && ex.InnerException != null) { WebException webException = ex.InnerException as WebException; HttpWebResponse webResponse = webException.Response as HttpWebResponse; if (webResponse != null) { if (webResponse.StatusCode == HttpStatusCode.Moved || webResponse.StatusCode == HttpStatusCode.MovedPermanently || webResponse.StatusCode == HttpStatusCode.Redirect || webResponse.StatusCode == HttpStatusCode.RedirectKeepVerb) { string redirectUrl = webResponse.Headers[HttpResponseHeader.Location]; if (!string.IsNullOrEmpty(redirectUrl)) { getHost = true; lock (deltas.SyncObject) deltas.PreferredHosts[preferredHostKey] = FetchHost(redirectUrl); Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose, "Get redirect URL by HTTP error succeed, method " + methodName + ":\r\n " + "Original: " + FetchHost(ws.Url) + "\r\n " + "Redirect: " + FetchHost(redirectUrl) + "\r\n"); } #region Fetch CacheKey try { XmlDocument errdoc = new XmlDocument(); string errorMessage = ex.InnerException.Message; string xmlstr = errorMessage.Substring(errorMessage.IndexOf("<?xml")); xmlstr = xmlstr.Substring(0, xmlstr.IndexOf("</soap:envelope>", StringComparison.InvariantCultureIgnoreCase) + "</soap:envelope>".Length); //I think the xml parser microsoft used internally is just a super parser, it can ignore everything. xmlstr = xmlstr.Replace("&", "&"); xmlstr = xmlstr.Replace("&", "&"); errdoc.LoadXml(xmlstr); XmlNodeList findnodelist = errdoc.GetElementsByTagName("CacheKey"); if (findnodelist.Count > 0 && !String.IsNullOrEmpty(findnodelist[0].InnerText)) { deltas.CacheKeys[keyType] = findnodelist[0].InnerText; } } catch (Exception exc) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "An error occured while getting CacheKey:\r\n" + "Service: " + ws.GetType().ToString() + "\r\n" + "MethodName: " + methodName + "\r\n" + "Message: " + exc.Message); } #endregion } } } if (!getHost) { Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "An error occured while getting CacheKey and Preferred host:\r\n" + "Service: " + ws.GetType().ToString() + "\r\n" + "MethodName: " + methodName + "\r\n" + "Message: " + ex.Message); lock (deltas.SyncObject) deltas.PreferredHosts[preferredHostKey] = originalHost; //If there's an error, we must set the host back to its original value. } } deltas.Save(); } lock (deltas.SyncObject) { if (originalHost != null && originalHost != String.Empty) { if (deltas.PreferredHosts.ContainsKey(preferredHostKey)) { ws.Url = originalUrl.Replace(originalHost, FetchHost(deltas.PreferredHosts[preferredHostKey])); } else { //This means the redirection URL returns respond content. lock (deltas.SyncObject) { deltas.PreferredHosts[preferredHostKey] = ws.Url; deltas.Save(); } Trace.WriteLineIf(Settings.TraceSwitch.TraceInfo, "The redirect URL returns correct result, use " + ws.Url + " for " + preferredHostKey); } } // Set cache key if (st == MsnServiceType.AB) { ((ABServiceBinding)ws).ABApplicationHeaderValue.CacheKey = deltas.CacheKeys[keyType]; } else if (st == MsnServiceType.Sharing) { ((SharingServiceBinding)ws).ABApplicationHeaderValue.CacheKey = deltas.CacheKeys[keyType]; } else if (st == MsnServiceType.Storage) { ((StorageService)ws).AffinityCacheHeaderValue.CacheKey = deltas.CacheKeys[keyType]; } } } }
public void Search_StateDefinesDepthAndCacheKeyTypeIsStateOnly_ThrowException(CacheMode cacheMode, CacheKeyType cacheKeyType) { var engine = new SearchEngine(cacheMode, cacheKeyType) { StateDefinesDepth = true }; engine.Search(new IncreasingNumberState(1, Player.Max), 1); }
/// <summary> /// memcache need not to implement this function. /// </summary> /// <param name="key"></param> /// <param name="type"></param> /// <returns></returns> public string QueryWithType(string key, CacheKeyType type) { throw new NotImplementedException(); }
public void Constructor_NoCacheMode_NoException(CacheKeyType cacheKeyType) { new SearchEngine(CacheMode.NoCache, cacheKeyType); }
public void Constructor_CacheKeyTypeSetToRightMode(CacheKeyType cacheKeyType) { var engine = new SearchEngine(CacheMode.NewCache, cacheKeyType); Assert.AreEqual(cacheKeyType, engine.CacheKeyType); }
public bool Set(string key, CacheKeyType type, string value, int timeToLive) { throw new NotImplementedException(); }
/// <summary> /// 获取参数封装入集合 /// </summary> /// <param name="paramterList"></param> /// <param name="gen"></param> /// <param name="paramterListBulider"></param> private static void GetParamters(List <Tuple <string, int, MethodInfo, Type> > outputParamters, ParameterInfo[] paramterList, ILGenerator gen, LocalBuilder paramterListBulider, bool use_cache, string sqlTextKey, out ParameterInfo scope_parameterInfo) { scope_parameterInfo = null; bool haschache_attr = paramterList.Any(x => x.GetCustomAttribute <DbCacheKeyAttribute>() != null); foreach (var paramter in paramterList) { if (!string.IsNullOrEmpty(sqlTextKey) && paramter.Name == sqlTextKey) { //跳过指定sql语句的参数 continue; } Type pType = paramter.ParameterType; Type eType = pType.GetElementType();//若为ref或out参数则eType为其原来类型 if (pType.GetInterface(SCOPE_ITEM) != null || (eType != null && eType.GetInterface(SCOPE_ITEM) != null)) { //IDbNetScope类型为事务处理变量,不能添加到参数中 scope_parameterInfo = paramter; continue; } LocalBuilder pTypeBulider = null; DbNetParamterDirection dir = DbNetParamterDirection.Input; CacheKeyType cacheKeyType = CacheKeyType.None; if (use_cache) { cacheKeyType = CacheKeyType.Bind; if (haschache_attr) { cacheKeyType = CacheKeyType.None; } var cache_attr = paramter.GetCustomAttribute <DbCacheKeyAttribute>(); if (cache_attr != null) { cacheKeyType = CacheKeyType.Bind; } } if (!paramter.IsOut && !pType.IsByRef) { pTypeBulider = gen.DeclareLocal(pType); gen.Emit(OpCodes.Ldarg, paramter.Position + 1); } else { dir = DbNetParamterDirection.InputAndOutPut; pTypeBulider = gen.DeclareLocal(eType); if (pType.IsByRef) { //获取ref参数的值 gen.Emit(OpCodes.Ldarg, paramter.Position + 1); GetRef(gen, pTypeBulider.LocalType); } } gen.Emit(OpCodes.Stloc, pTypeBulider); if (pTypeBulider.LocalType.IsClass) { Label isNullLabel = gen.DefineLabel(); gen.Emit(OpCodes.Ldloc, pTypeBulider); gen.Emit(OpCodes.Ldnull); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Brfalse, isNullLabel); gen.Emit(OpCodes.Call, MethodHelper.defaultMethod.MakeGenericMethod(pTypeBulider.LocalType)); gen.Emit(OpCodes.Stloc, pTypeBulider); gen.MarkLabel(isNullLabel); } if (paramter.IsOut || pType.IsByRef) { //输出参数获取下阶段备用 outputParamters.Add(new Tuple <string, int, MethodInfo, Type>(paramter.Name, paramter.Position + 1, null, eType)); } if (pTypeBulider.LocalType == typeof(string) || pTypeBulider.LocalType.IsValueType || pTypeBulider.LocalType.IsArray) { //添加结构体或者string到集合 gen.Emit(OpCodes.Ldloc, paramterListBulider); gen.Emit(OpCodes.Ldstr, paramter.Name); gen.Emit(OpCodes.Ldloc, pTypeBulider); gen.Emit(OpCodes.Ldc_I4, (int)dir); gen.Emit(OpCodes.Ldc_I4, paramter.Position); gen.Emit(OpCodes.Ldc_I4, (int)SourceType.FromArg); gen.Emit(OpCodes.Ldc_I4, (int)cacheKeyType); gen.Emit(OpCodes.Call, MethodHelper.paramterMethod.MakeGenericMethod(pTypeBulider.LocalType)); } else { //如果参数是类则需进一步处理 var pinfo = pTypeBulider.LocalType.GetProperties(); var cache_attr_c = paramter.GetCustomAttribute <DbCacheKeyAttribute>(); foreach (var p in pinfo) { DbParamterAttribute attr_p = p.GetCustomAttribute <DbParamterAttribute>(true); bool except = false; string name = string.Empty; DbNetParamterDirection pdir = DbNetParamterDirection.Input; CacheKeyType p_cacheKeyType = CacheKeyType.None; if (use_cache) { p_cacheKeyType = CacheKeyType.Bind; if (haschache_attr) { p_cacheKeyType = CacheKeyType.None; } if (cache_attr_c != null) { p_cacheKeyType = CacheKeyType.Bind; } if (attr_p != null && attr_p.CacheKey != CacheKeyType.Default) { p_cacheKeyType = attr_p.CacheKey; } } if (paramter.IsOut) { //输出参数获取下阶段备用 outputParamters.Add(new Tuple <string, int, MethodInfo, Type>(paramter.Name, paramter.Position + 1, p.GetSetMethod(), p.PropertyType)); pdir = DbNetParamterDirection.Output; } else if (pType.IsByRef) { //输出参数获取下阶段备用 outputParamters.Add(new Tuple <string, int, MethodInfo, Type>(paramter.Name, paramter.Position + 1, p.GetSetMethod(), p.PropertyType)); pdir = DbNetParamterDirection.InputAndOutPut; } if (attr_p != null) { except = attr_p.Except; name = attr_p.Name; pdir = attr_p.ParameterDirection; } if (string.IsNullOrEmpty(name)) { name = p.Name; } if (!except) { gen.Emit(OpCodes.Ldloc, paramterListBulider); gen.Emit(OpCodes.Ldstr, name); gen.Emit(OpCodes.Ldloc, pTypeBulider); gen.Emit(OpCodes.Call, p.GetGetMethod()); gen.Emit(OpCodes.Ldc_I4, (int)pdir); gen.Emit(OpCodes.Ldc_I4, paramter.Position); gen.Emit(OpCodes.Ldc_I4, (int)SourceType.FromClass); gen.Emit(OpCodes.Ldc_I4, (int)p_cacheKeyType); gen.Emit(OpCodes.Call, MethodHelper.paramterMethod.MakeGenericMethod(p.PropertyType)); } } } } }