コード例 #1
0
        public bool SetValue(string key, object value, TimeSpan duration, bool requiredNotExists = false)
        {
            if (requiredNotExists)
            {
                var exists = _innerCache.Contains(key);

                if (exists)
                {
                    return(false);
                }
            }

            if (duration == TimeSpan.Zero)
            {
                _innerCache.Set(key, value, new System.Runtime.Caching.CacheItemPolicy()
                {
                    AbsoluteExpiration = System.Runtime.Caching.ObjectCache.InfiniteAbsoluteExpiration,
                    //UpdateCallback = this.OnUpdateCallback,
                    RemovedCallback = this.OnRemovedCallback,
                });
            }
            else
            {
                _innerCache.Set(key, value, new System.Runtime.Caching.CacheItemPolicy()
                {
                    SlidingExpiration = duration,
                    //UpdateCallback = this.OnUpdateCallback,
                    RemovedCallback = this.OnRemovedCallback,
                });
            }

            return(true);
        }
コード例 #2
0
        public object GetValue(string key, Func <string, Tuple <object, TimeSpan> > valueCreator)
        {
            if (valueCreator == null)
            {
                return(_innerCache.Get(key));
            }

            var result = valueCreator(key);

#if !CORE_CLR
            return(_innerCache.AddOrGetExisting(key, result.Item1, new System.Runtime.Caching.CacheItemPolicy()
            {
                SlidingExpiration = result.Item2,
                RemovedCallback = this.OnRemovedCallback,
            }));
#else
            if (!this.Exists(key))
            {
                var options = new MemoryCacheEntryOptions();
                options.SlidingExpiration = result.Item2;
                options.RegisterPostEvictionCallback(this.OnPostEvictionCallback);

                return(_innerCache.Set(key, result.Item1, options));
            }
            else
            {
                return(_innerCache.Get(key));
            }
#endif
        }
コード例 #3
0
        /// <inheritdoc />
        public void Set <T>(string key, Func <T> factory, TimeSpan?lifeSpan)
        {
            var objectToAdd         = factory();
            var cacheItemExpiryDate = GetCacheItemExpiryDate(lifeSpan);

            cache.Set(key, objectToAdd, cacheItemExpiryDate);
        }
コード例 #4
0
ファイル: MemoryCache.cs プロジェクト: hongweichang/NFinal2
        public override void Set(string key, byte[] value, int minutes)
        {
#if !(NETCORE || CORE)
            _memoryCache.Set(key, value, _cacheItemPolicy);
#else
            Microsoft.Extensions.Caching.Memory.ICacheEntry cacheEntry = _memoryCache.CreateEntry(key);
            cacheEntry.SlidingExpiration = TimeSpan.FromMinutes(this.minutes);
            cacheEntry.Value             = value;
#endif
        }
コード例 #5
0
ファイル: MemoryCache.cs プロジェクト: AsWinds/Smart
        public T Set <T>(string key, CacheInfo <T> cache) where T : class
        {
            var oldCache  = _cache.Get(key);
            var cacheItem = new System.Runtime.Caching.CacheItem(key, cache.Value);
            var policy    = new System.Runtime.Caching.CacheItemPolicy();

            policy.SlidingExpiration = cache.SlidingExpiration;
            _cache.Set(cacheItem, policy);
            return(oldCache == null ? null : (T)oldCache);
        }
コード例 #6
0
        public static string GetString(string name)
        {
            string result = null;

            if (x.Contains(name))
            {
                var obj = x[name];

                result = (string)(obj == DBNull.Value ? null : obj);
            }
            else
            {
                using (var db = new CC.Data.ccEntities())
                {
                    try
                    {
                        var item = db.GlobalStrings.SingleOrDefault(f => f.Name == name);
                        if (item != null)
                        {
                            result = item.Value;
                        }
                    }
                    catch (Exception)
                    {
                        return(name + " - value not found");
                    }
                }
                if (result == null)
                {
                    x.Set(name, DBNull.Value, new System.Runtime.Caching.CacheItemPolicy());
                }
                else
                {
                    x.Set(name, result, new System.Runtime.Caching.CacheItemPolicy());
                }
            }
            return(result);
        }
コード例 #7
0
        public void Set(string key, object value)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            _cache.Set(key, value, new System.Runtime.Caching.CacheItemPolicy());
        }
コード例 #8
0
ファイル: MemoryCache.cs プロジェクト: zhangzheng1205/Smart
        void ICache.Set(string key, CacheInfo cache)
        {
            var cacheItem = new System.Runtime.Caching.CacheItem(key, cache.Value);
            var policy    = new System.Runtime.Caching.CacheItemPolicy();

            if (cache.AbsoluteExpiration.Ticks > 0)
            {
                policy.AbsoluteExpiration = cache.AbsoluteExpiration;
            }
            if (cache.SlidingExpiration.Ticks > 0)
            {
                policy.SlidingExpiration = cache.SlidingExpiration;
            }
            _cache.Set(cacheItem, policy);
        }
コード例 #9
0
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiry">过期时间</param>
        /// <returns></returns>
        public bool Add(string key, object value, TimeSpan?expiry = null)
        {
#if net40
            var cachePolicy = new System.Runtime.Caching.CacheItemPolicy();
            if (expiry.HasValue)
            {
                cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.Add(expiry.Value);
            }
            var item = new System.Runtime.Caching.CacheItem(key, value);
            Cache.Set(item, cachePolicy);
#endif
#if netstandard2_0
            using (var entry = Cache.CreateEntry(key))
            {
                entry.Value = value;
                entry.AbsoluteExpirationRelativeToNow = expiry;
            }
#endif
            return(true);
        }
コード例 #10
0
 public void Set(string key, object value, DateTimeOffset expirationTime)
 {
     _cache.Set(key, value, expirationTime);
 }
コード例 #11
0
        void CheckCacheAndRedirect()
        {
            PageReference target;
            int           cacheTime = GetAttributeValue("CacheTime").AsInteger();

            //
            // If they specify "forever", then cache for 1 year. If it's a leap year then you are out of luck.
            //
            if (cacheTime <= 0)
            {
                cacheTime = 365 * 24 * 60;
            }

            target = new PageReference(GetAttributeValue("ContentPage"), new Dictionary <string, string>());

            foreach (var urlKey in GetAttributeValues("URLKey"))
            {
                bool   hasValueInUrl = CurrentPageReference.QueryString.AllKeys.Select(s => s.ToLower()).Contains(urlKey.ToLower());
                string key           = CacheKey(urlKey);
                string value         = null;

                //
                // Try to get the value from the URL and then from the cache.
                //
                if (hasValueInUrl)
                {
                    value = PageParameter(urlKey);
                }
                else
                {
                    value = ( string )_cache[key];
                }

                if (value == null)
                {
                    //
                    // No value. They need to be sent to the Setup Page or the parent page.
                    //
                    if (!string.IsNullOrEmpty(GetAttributeValue("SetupPage")))
                    {
                        target = new PageReference(GetAttributeValue("SetupPage"));
                    }
                    else
                    {
                        var pageCache = PageCache.Read(RockPage.PageId);
                        if (pageCache != null && pageCache.ParentPage != null)
                        {
                            target = new PageReference(pageCache.ParentPage.Guid.ToString());
                        }
                        else
                        {
                            nbWarning.Text = "No Setup Page was defined and no parent page could be found.";
                            return;
                        }
                    }

                    break;
                }

                //
                // We have a value, save it to the cache.
                //
                _cache.Set(key, value, DateTimeOffset.Now.AddMinutes(cacheTime));
                target.Parameters.AddOrReplace(urlKey, value);
            }

            Redirect(target.BuildUrl());
        }
コード例 #12
0
 public static void Set(string key, Schema schema)
 {
     EntryCount++;
     _memCache.Set(key, schema, new System.Runtime.Caching.CacheItemPolicy());
 }
コード例 #13
0
 public void Set(string key, object value)
 {
     _memoryCache.Set(key, value, DateTimeOffset.MaxValue);
 }
コード例 #14
0
ファイル: Cache.cs プロジェクト: PowerOlive/Atlas-5
 public void Set(string key, T value, TimeSpan timeToLive)
 {
     cache.Set(key, value, DateTimeOffset.Now.Add(timeToLive));
 }
コード例 #15
0
 public object this[string key]
 {
     get { return(_cache.Get(key)); }
     set { _cache.Set(key, value, DateTimeOffset.Now.AddYears(1)); }
 }
コード例 #16
0
        void CheckCacheAndRedirect()
        {
            PageReference target;
            string        key = CacheKey();
            string        value;
            int           cacheTime = GetAttributeValue("CacheTime").AsInteger();

            //
            // If they specify "forever", then cache for 1 year. If it's a leap year then you are out of luck.
            //
            if (cacheTime <= 0)
            {
                cacheTime = 365 * 24 * 60;
            }

            //
            // Try to get the value from the URL and then from the cache.
            //
            value = PageParameter(GetAttributeValue("URLKey"));
            if (string.IsNullOrEmpty(value))
            {
                value = ( string )_cache[key];
            }

            if (!string.IsNullOrEmpty(value))
            {
                //
                // We have a value, save it to the cache.
                //
                target            = new PageReference(GetAttributeValue("ContentPage"));
                target.Parameters = new Dictionary <string, string> {
                    { GetAttributeValue("URLKey"), value }
                };
                _cache.Set(key, value, DateTimeOffset.Now.AddMinutes(cacheTime));
            }
            else
            {
                //
                // No value. They need to be sent to the Setup Page or the parent page.
                //
                if (!string.IsNullOrEmpty(GetAttributeValue("SetupPage")))
                {
                    target = new PageReference(GetAttributeValue("SetupPage"));
                }
                else
                {
                    var pageCache = PageCache.Read(RockPage.PageId);
                    if (pageCache != null && pageCache.ParentPage != null)
                    {
                        target = new PageReference(pageCache.ParentPage.Guid.ToString());
                    }
                    else
                    {
                        nbWarning.Text = "No Setup Page was defined and no parent page could be found.";
                        return;
                    }
                }
            }

            Redirect(target.BuildUrl());
        }
コード例 #17
0
 private T SetMemory <T>(string key, TimeSpan timespan, T value)
 {
     _memorycache.Set(key, value, DateTimeOffset.UtcNow.Add(timespan));
     return(value);
 }
コード例 #18
0
 public void Add <T>(string key, CacheItem <T> item)
 {
     _cache.Set(key, item, item.Expires);
 }
コード例 #19
0
ファイル: MemoryCache.cs プロジェクト: ilkerhalil/KVLite
        /// <summary>
        ///   Adds given value with the specified expiry time and refresh internal.
        /// </summary>
        /// <typeparam name="TVal">The type of the value.</typeparam>
        /// <param name="partition">The partition.</param>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="utcExpiry">The UTC expiry time.</param>
        /// <param name="interval">The refresh interval.</param>
        /// <param name="parentKeys">
        ///   Keys, belonging to current partition, on which the new item will depend.
        /// </param>
        protected override void AddInternal <TVal>(string partition, string key, TVal value, Instant utcExpiry, Duration interval, IList <string> parentKeys)
        {
            if (Log.IsDebugEnabled())
            {
                Log.DebugFormat(DebugMessages.AddItem, partition, key, Settings.CacheName, utcExpiry, interval);
            }

            byte[] serializedValue;
            bool   compressed;

            try
            {
                using (var serializedStream = new PooledMemoryStream())
                {
                    Serializer.SerializeToStream(value, serializedStream);

                    if (serializedStream.Length > Settings.MinValueLengthForCompression)
                    {
                        // Stream is too long, we should compress it.
                        using (var compressedStream = new PooledMemoryStream())
                        {
                            using (var compressionStream = Compressor.CreateCompressionStream(compressedStream))
                            {
                                serializedStream.Position = 0L;
                                serializedStream.CopyTo(compressionStream);
                            }
                            serializedValue = compressedStream.ToArray();
                            compressed      = true;
                        }
                    }
                    else
                    {
                        // Stream is shorter than specified threshold, we can store it as it is.
                        serializedValue = serializedStream.ToArray();
                        compressed      = false;
                    }
                }
            }
            catch (Exception ex)
            {
                LastError = ex;
                Log.ErrorException(ErrorMessages.InternalErrorOnSerialization, ex, value);
                throw new ArgumentException(ErrorMessages.NotSerializableValue, ex);
            }

            var policy = (interval == Duration.Zero)
                ? new SystemCacheItemPolicy {
                AbsoluteExpiration = utcExpiry.ToDateTimeOffset()
            }
                : new SystemCacheItemPolicy {
                SlidingExpiration = interval.ToTimeSpan()
            };

            if (parentKeys != null && parentKeys.Count > 0)
            {
                policy.ChangeMonitors.Add(_store.CreateCacheEntryChangeMonitor(parentKeys.Select(pk => SerializeCacheKey(partition, pk))));
            }

            var cacheValue = new CacheValue {
                Value = serializedValue, Compressed = compressed, UtcCreation = Clock.GetCurrentInstant()
            };

            _store.Set(SerializeCacheKey(partition, key), cacheValue, policy);
        }