Exemplo n.º 1
0
        public void TestMethodGet()
        {
            DistCache.Add("key2", "testServer", ProviderName);
            var result = DistCache.Get <string>("key2", ProviderName);

            Assert.AreEqual("testServer", result);
        }
Exemplo n.º 2
0
        public override void Remove(string prefix, string key, Guid timestamp)
        {
            string fullName = this.GetFullName(prefix, key);

            DistCache.Remove(fullName);
            cacheKeys.Remove(fullName);
        }
Exemplo n.º 3
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        DistCache.Add("myname", TextBox1.Text);

        //給此變數設定 Expiration
        //DistCache.Add("myname", TextBox1.Text, DateTime.Today.AddDays(1) - DateTime.Now);
    }
Exemplo n.º 4
0
        /// <summary>
        /// 获取缓存数据。
        /// </summary>
        /// <param name="key">键。</param>
        /// <returns>缓存数据。</returns>
        private static object GetCacheValue(string key)
        {
            object value = null;
            bool   useMemcached, useWebCache, useBothCache;
            int    cacheTimeout;
            string versionKey;

            AnalyzeCacheKey(key, out useMemcached, out useWebCache, out useBothCache, out cacheTimeout, out versionKey);

            if (useBothCache) //使用双缓存
            {
                object dotNetCacheVersion = _cache.Get(versionKey);
                object memcachedVersion   = DistCache.Get(versionKey);

                //如果Web Cache和Memcached中的缓存版本不相等,则表示缓存的数据已发生变化,需重新从数据库读取并更新缓存
                if (dotNetCacheVersion == null || memcachedVersion == null || dotNetCacheVersion.ToString() != memcachedVersion.ToString())
                {
                    value = null;
                }
                else
                {
                    value = _cache.Get(key);
                }
            }
            else if (useWebCache)
            {
                value = _cache.Get(key);
            }
            else if (useMemcached)
            {
                value = DistCache.Get(key);
            }

            return(value);
        }
Exemplo n.º 5
0
        public void Get_Multiple_Positive_Test()
        {
            Debug.WriteLine("-------------Get_Multiple_Positive_Test()------------");

            string[] keys = new string[10];

            using (CalcTimeSpan calc = new CalcTimeSpan("Time for Setting"))
            {
                for (int i = 0; i < 10; i++)
                {
                    DistCache.Add(i.ToString(), i * 2);
                    keys[i] = i.ToString();
                }
            }

            using (CalcTimeSpan calc = new CalcTimeSpan("Time for Getting"))
            {
                IDictionary <string, object> _retVal = DistCache.Get(keys);

                for (int i = 0; i < 10; i++)
                {
                    Assert.IsTrue(((int)_retVal[keys[i]]) == (i * 2));
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 根据表名称清除对应的缓存,在添加缓存的时候加上涉及到的表名称
        /// </summary>
        /// <param name="tbName"></param>
        public void RemoveKeyDicByTbName(string tbName)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(tbName))
                {
                    return;
                }
                tbName = tbName.ToLower();
                List <MemcacheKey> MemcacheKeyList = GetMemcacheKeyLis();

                var keyList = MemcacheKeyList.Where(t => t.RelationTableName.ToLower().Contains(tbName)).Select(m => m.Key).ToList();

                MemcacheKeyList.RemoveAll(t => t.RelationTableName.ToLower().Contains(tbName));
                DistCache.Add(KeyDic, MemcacheKeyList);

                keyList = keyList.Distinct().ToList();
                foreach (var item in keyList)
                {
                    DistCache.Remove(item);
                }
            }
            catch
            {
            }
        }
Exemplo n.º 7
0
        public void Add(string key, object value, string tbNames = "", string description = "")
        {
            if (value == null || string.IsNullOrWhiteSpace(key))
            {
                return;
            }
            var a = DistCache.Add(key, value);

            AddKeyDic(key, tbNames, description, DistCache.DefaultExpireTime);
        }
Exemplo n.º 8
0
        public void Add(string key, object value, int expireTime, string tbNames = "", string description = "")
        {
            if (value == null || string.IsNullOrWhiteSpace(key))
            {
                return;
            }
            var a = DistCache.Add(key, value, TimeSpan.FromMinutes(expireTime));

            AddKeyDic(key, tbNames, description, expireTime);
        }
 /// <summary>
 /// 使用set方式增加/更新缓存
 /// </summary>
 /// <param name="strKey">关键字</param>
 /// <param name="objValue">值</param>
 /// <param name="isSetExpireTime">true:过期时间默认为配置节defaultExpireSeconds;false:永不过期</param>
 /// <param name="cacheType">缓存类型,0=memcached,1=redis</param>
 /// <returns></returns>
 //public static bool Set(string strKey, object objValue, bool isSetExpireTime = true, int cacheType = 1)
 //{
 //    if (cacheType == 0)
 //    {
 //        return DistCache.Set(strKey, objValue, isSetExpireTime);
 //    }
 //    else
 //    {
 //        return RedisManager.Set<object>(strKey, objValue, isSetExpireTime);
 //    }
 //}
 public static bool Set <T>(string strKey, T objValue, bool isSetExpireTime = true, int cacheType = 1)
 {
     if (cacheType == 0)
     {
         return(DistCache.Set(strKey, objValue, isSetExpireTime));
     }
     else
     {
         return(RedisManager.Set <T>(strKey, objValue, isSetExpireTime));
     }
 }
Exemplo n.º 10
0
 public static bool SetVal(string strKey, object objValue)
 {
     if (lNumofMilliSeconds == 0)
     {
         return(DistCache.Add(strKey, objValue));
     }
     else
     {
         return(DistCache.Add(strKey, objValue, lNumofMilliSeconds));
     }
 }
 /// <summary>
 /// 使用set方式增加/更新缓存
 /// </summary>
 /// <param name="strKey">关键字</param>
 /// <param name="objValue">值</param>
 /// <param name="lNumofSeconds">过期时间,单位秒</param>
 /// <param name="cacheType">缓存类型,0=memcached,1=redis</param>
 /// <returns></returns>
 public static bool Set(string strKey, object objValue, long lNumofSeconds, int cacheType = 1)
 {
     if (cacheType == 0)
     {
         return(DistCache.Set(strKey, objValue, lNumofSeconds));
     }
     else
     {
         return(RedisManager.Set <object>(strKey, objValue, lNumofSeconds));
     }
 }
 //public static bool Add(string strKey, object objValue)
 //{
 //    return DistCache.Add(strKey, objValue);
 //}
 /// <summary>
 /// 使用add方式增加缓存(已存在则无法更新)
 /// </summary>
 /// <param name="strKey">关键字</param>
 /// <param name="objValue">值</param>
 /// <param name="isSetExpireTime">true:过期时间默认为配置节defaultExpireSeconds;false:永不过期</param>
 /// <returns></returns>
 public static bool Add(string strKey, object objValue, bool isSetExpireTime = true, int cacheType = 1)
 {
     if (cacheType == 0)
     {
         return(DistCache.Add(strKey, objValue, isSetExpireTime));
     }
     else
     {
         return(RedisManager.Add <object>(strKey, objValue, isSetExpireTime));
     }
 }
 public static object Remove(string strKey, int cacheType = 1)
 {
     if (cacheType == 0)
     {
         return(DistCache.Remove(strKey));
     }
     else
     {
         return(RedisManager.Remove(strKey));
     }
 }
        //public static IDictionary<string, object> Get(params string[] keys)
        //{
        //    return DistCache.Get(keys);
        //}

        public static T Get <T>(string strKey, int cacheType = 1)
        {
            if (cacheType == 0)
            {
                return(DistCache.Get <T>(strKey));
            }
            else
            {
                return(RedisManager.Get <T>(strKey));
            }
        }
Exemplo n.º 15
0
        public bool CompressAdd(string key, object value, int expireTime, string tbNames = "", string description = "")
        {
            if (value == null || string.IsNullOrWhiteSpace(key))
            {
                return(false);
            }
            AddKeyDic(key, tbNames, description, expireTime);
            byte[] compressData = CompressHelper.Compress(value);
            var    rst          = DistCache.Add(key, compressData, TimeSpan.FromMinutes(expireTime));

            return(rst);
        }
Exemplo n.º 16
0
 public static bool SetVal(string strKey, RstVar objValue)
 {
     if (lNumofMilliSeconds == 0)
     {
         return(DistCache.Add(strKey, JsonHelper.Serialize(objValue)));
     }
     else
     {
         return(DistCache.Add(strKey, JsonHelper.Serialize(objValue), lNumofMilliSeconds));
     }
     //return DistCache.Add(strKey, JsonHelper.Serialize(objValue));
 }
Exemplo n.º 17
0
        /// <summary>
        /// 保存缓存数据至Memcached。
        /// </summary>
        /// <param name="key">键。</param>
        /// <param name="value">要缓存的数据。</param>
        /// <param name="cacheTimeout">缓存过期时间。</param>
        /// <returns>缓存是否成功。</returns>
        private static bool SetMemcachedValue(string key, object value, int cacheTimeout)
        {
            bool success  = false;
            int  tryCount = ConfigUtil.MemcachedTryCount;

            //Memcached Set/Get数据超过2s的,系统记录警告信息
            System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

            for (int i = 0; i < tryCount; i++)
            {
                try
                {
                    if (cacheTimeout <= 0)
                    {
                        success = DistCache.Add(key, value);
                    }
                    else
                    {
                        success = DistCache.Add(key, value, cacheTimeout * 1000);
                    }

                    if (success)
                    {
                        break;
                    }

                    LogUtil.Error(String.Format("第【{0}】次尝试向Memcached保存Key为【{1}】的数据失败!", i, key));
                }
                catch (Exception ex)
                {
                    LogUtil.Error(String.Format("第【{0}】次尝试向Memcached保存Key为【{1}】的数据失败,{2}", i, key, ex.Message), ex);
                }
            }

            //Memcached Set/Get数据超过2s的,系统记录警告信息
            if (sw != null)
            {
                sw.Stop();

                long duration = sw.ElapsedMilliseconds / 1000;

                if (duration > ConfigUtil.WarnDuration)
                {
                    LogUtil.Warn(String.Format("向Memcached保存Key为【{0}】的数据的时间超过【{1}】s!", key, ConfigUtil.WarnDuration));
                }

                sw = null;
            }


            return(success);
        }
Exemplo n.º 18
0
        public static string GetVal(string strKey)
        {
            object obj = DistCache.Get(strKey);

            if (obj != null)
            {
                return(obj.ToString());
            }
            else
            {
                return("");
            }
        }
Exemplo n.º 19
0
        public T DecompressGet <T>(string key)
        {
            var decompressData = DistCache.Get <byte[]>(key);

            if (decompressData != null)
            {
                return(CompressHelper.Decompress <T>(decompressData));
            }
            //return default(T);
            else
            {
                return(default(T));
            }
        }
Exemplo n.º 20
0
        public async void AsyncAddKeyDic(string key, string tbNames = "", string description = "", long expireTime = 60)
        {
            try
            {
                await Task.Delay(1);

                if (string.IsNullOrWhiteSpace(key))
                {
                    return;
                }
                List <MemcacheKey> MemcacheKeyList = GetMemcacheKeyLis();
                if (MemcacheKeyList == null)
                {
                    MemcacheKeyList = new List <MemcacheKey>();
                }
                //清除过期的key
                DateTime cTime = DateTime.MinValue;
                MemcacheKeyList = MemcacheKeyList.Where(k =>
                {
                    DateTime.TryParse(k.CreateTime, out cTime);
                    return(cTime > DateTime.Now.AddMinutes(-1 * k.ExpireTime));
                }).ToList();
                var item = MemcacheKeyList.Where(m => m.Key == key).SingleOrDefault();
                if (item != null)
                {
                    item.Key               = key;
                    item.CreateTime        = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    item.RelationTableName = tbNames;
                    item.ExpireTime        = expireTime;
                    item.Description       = description;
                }
                else
                {
                    MemcacheKeyList.Add(new MemcacheKey()
                    {
                        Key               = key,
                        CreateTime        = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        RelationTableName = tbNames,
                        ExpireTime        = expireTime,
                        Description       = description
                    });
                }
                var a = DistCache.Add(KeyDic, MemcacheKeyList);
            }
            catch
            {
            }
        }
Exemplo n.º 21
0
        public override void ClearAll()
        {
            DistCache.RemoveAll();

            IList <string> keys = new List <string>();

            foreach (KeyValuePair <string, string> kvp in cacheKeys)
            {
                keys.Add(kvp.Key);
            }

            foreach (string key in keys)
            {
                cacheKeys.Remove(key);
            }
        }
Exemplo n.º 22
0
        public void TestMethodAddSliding()
        {
            string key    = "TestMethodAddSliding";
            string value  = Guid.NewGuid().ToString();
            var    result = DistCache.AddForSliding(key, value, TimeSpan.FromSeconds(1), ProviderName);

            Assert.AreEqual(true, result);
            Thread.Sleep(500);
            var entity = DistCache.Get <string>(key, ProviderName);

            Assert.IsNotNull(entity);
            Assert.AreEqual(value, entity);
            Thread.Sleep(600);
            entity = DistCache.Get <string>(key, ProviderName);
            Assert.IsNotNull(entity);
            Assert.AreEqual(value, entity);
        }
Exemplo n.º 23
0
        public void CheckExpire_Max_Positive_Test()
        {
            Debug.WriteLine("-------------CheckExpire_Max_Positive_Test()------------");
            string strKey   = "name";
            string strValue = "Fahad";

            using (CalcTimeSpan calc = new CalcTimeSpan("Time for Setting"))
            {
                Assert.IsTrue(DistCache.Add(strKey, strValue));
            }

            System.Threading.Thread.Sleep(new TimeSpan(0, 0, 5));

            using (CalcTimeSpan calc = new CalcTimeSpan("Time for Getting"))
            {
                Assert.IsNotNull(DistCache.Get(strKey));
            }
        }
Exemplo n.º 24
0
 public override bool Add <T>(string prefix, string key, T value, TimeSpan duration)
 {
     lock (objLock)
     {
         if (duration <= TimeSpan.Zero)
         {
             duration = this.MaxDuration;
         }
         string fullName = this.GetFullName(prefix, key);
         bool   b1       = DistCache.Add(fullName, value);
         bool   b2       = cacheKeys.ContainsKey(fullName);
         if (b1 && !b2)
         {
             cacheKeys.Add(fullName, fullName);
         }
         return(b1);
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// 模糊匹配删除缓存
        /// </summary>
        /// <param name="key"></param>
        public void RemoveLikeKey(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return;
            }
            var MemcacheKeyList = GetMemcacheKeyLis();

            var keyList = MemcacheKeyList.Where(m => m.Key.ToLower().IndexOf(key.ToLower()) >= 0).Select(mm => mm.Key).ToList();

            MemcacheKeyList.RemoveAll(m => keyList.Contains(m.Key));
            DistCache.Add(KeyDic, MemcacheKeyList);

            foreach (var item in keyList)
            {
                DistCache.Remove(item);
            }
        }
Exemplo n.º 26
0
        public void Get_Template_Positive_Test()
        {
            Debug.WriteLine("-------------Get_Template_Positive_Test()------------");
            string strKey      = "firstname";
            string strValue    = "Fahad";
            string strReturned = string.Empty;

            using (CalcTimeSpan calc = new CalcTimeSpan("Time for Setting"))
            {
                Assert.IsTrue(DistCache.Add(strKey, strValue), "Error adding value");
            }

            using (CalcTimeSpan calc = new CalcTimeSpan("Time for Getting"))
            {
                strReturned = DistCache.Get <string>(strKey);
            }

            Assert.IsTrue(strValue.Equals(strReturned), string.Format("Not the same: {0}", strReturned));
        }
Exemplo n.º 27
0
        /// <summary>
        /// 获取一个key数据
        /// </summary>
        /// <typeparam name="T">泛型数据</typeparam>
        /// <param name="strKey">key</param>
        /// <returns>泛型数据</returns>
        public static T GetVal <T>(string strKey)
        {
            T t = DistCache.Get <T>(strKey);

            if (t == null)
            {
                object obj = DistCache.Get(strKey);
                if (obj == null)
                {
                    return(t);
                }
                T rst = JsonHelper.Deserialize <T>(obj.ToString());
                if (rst == null)
                {
                    return(t);
                }
                t = rst;
            }
            return(t);
            //return DistCache.Get<T>(strKey);
        }
Exemplo n.º 28
0
        public override void Clear(string prefix)
        {
            if (string.IsNullOrWhiteSpace(prefix))
            {
                return;
            }
            IList <string> keys = new List <string>();

            foreach (KeyValuePair <string, string> kvp in cacheKeys)
            {
                if (kvp.Key.Contains(prefix))
                {
                    DistCache.Remove(kvp.Key);
                    keys.Add(kvp.Key);
                }
            }

            foreach (string key in keys)
            {
                cacheKeys.Remove(key);
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// 批量指定KEY清除缓存
 /// </summary>
 /// <param name="keys"></param>
 public void RemoveKeyDic(string keys)
 {
     try
     {
         if (string.IsNullOrWhiteSpace(keys))
         {
             return;
         }
         List <MemcacheKey> MemcacheKeyList = GetMemcacheKeyLis();
         var keyArray = keys.Split(',').ToList();
         MemcacheKeyList.RemoveAll(m => !string.IsNullOrWhiteSpace(m.Key) && keyArray.Contains(m.Key));
         DistCache.Add(KeyDic, MemcacheKeyList);
         foreach (var key in keyArray)
         {
             if (!string.IsNullOrWhiteSpace(keys))
             {
                 DistCache.Remove(key);
             }
         }
     }
     catch
     {
     }
 }
Exemplo n.º 30
0
        public void TestMethodAdd()
        {
            var result = DistCache.Add("key1", "testServer", ProviderName);

            Assert.AreEqual(true, result);
        }