public void InsertData(IProcessManagerData data)
        {
            Type typeParameterType = data.GetType();

            MethodInfo md = GetType().GetTypeInfo().GetMethods().First(m => m.Name == "GetMemoryData" && m.GetParameters()[0].Name == "data");
            //MethodInfo genericMd = md.MakeGenericMethod(typeParameterType);
            MethodInfo genericMd = md.MakeGenericMethod(typeof(IProcessManagerData));

            lock (_memoryCacheLock)
            {
                var memoryData = genericMd.Invoke(this, new object[] { data });

                string key = data.CorrelationId.ToString();

                //if (!Cache.Contains(key))
                //{
                //    Cache.Set(key, memoryData, _policy);
                //}
                //else
                //{
                //    throw new ArgumentException(string.Format("ProcessManagerData with CorrelationId {0} already exists in the cache.", key));
                //}

                if (!_provider.Contains(key))
                {
                    _provider.Add(key, memoryData, _absoluteExpiry);
                }
                else
                {
                    throw new ArgumentException(string.Format("ProcessManagerData with CorrelationId {0} already exists in the cache.", key));
                }
            }
        }
Ejemplo n.º 2
0
        public int ReserveId <T>(TimeSpan howLong)
        {
            var cacheKey = GetCacheKey <T>();
            var idGroup  = _cache.Get(cacheKey);

            if (idGroup == null || !idGroup.Any())
            {
                //then we need to fill this group
                var idsFromSource = idSource.GetIds <T>(FetchSize);
                idGroup.AddRange(idsFromSource);
            }

            if (!idGroup.Any())
            {
                throw new Exception("Failed to get new id:s from source");
            }

            var nextId = idGroup.FirstOrDefault();

            idGroup.Remove(nextId);

            _cache.Put(cacheKey, idGroup, TimeSpan.FromDays(365));

            var reserveKey = GetReservationKey <T>(nextId);

            if (_cache.Contains(reserveKey))
            {
                throw new Exception("ID " + nextId + " has already been reserved");
            }

            _cache.Put(reserveKey, nextId, howLong);
            return(nextId);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 正常讀取緩存數據:緩存中沒有,則執行獲取數據方法
        /// </summary>
        /// <typeparam name="T">緩存值類型</typeparam>
        /// <param name="cacheKey">key</param>
        /// <param name="acquirer">獲取原始數據方法</param>
        /// <param name="cachePolicy">緩存過期策略</param>
        /// <returns>緩存結果</returns>
        private T GetCahcheValueByCommonRead <T>(CacheKey cacheKey, Func <T> acquirer, CachePolicy cachePolicy)
        {
            string strKey = cacheKey.Key;

            if (cacheProvider.Contains(strKey))
            {
                var value = cacheProvider.Get <T>(strKey);
                ProlongCacheValueLifeTime(cacheKey, cachePolicy, value);
                return(value);
            }
            else
            {
                if (acquirer == null)
                {
                    return(default(T));
                }
                using (cacheProvider.EnterReadLock())
                {
                    if (!cacheProvider.Contains(strKey))
                    {
                        var value = acquirer();
                        this.Set(cacheKey, value, cachePolicy);

                        return(value);
                    }
                }

                return(this.Get <T>(strKey));
            }
        }
Ejemplo n.º 4
0
 public T Get <T>(string key)
 {
     GuardHelper.ArgumentNotEmpty(() => key);
     if (cacheProvider.Contains(key))
     {
         return(cacheProvider.Get <T>(key));
     }
     else
     {
         return(default(T));
     }
 }
Ejemplo n.º 5
0
        public void Intercept(IInvocation invocation)
        {
            var cacheAttr = GetCacheResultAttribute(invocation);

            if (cacheAttr == null)
            {
                invocation.Proceed();
                return;
            }

            string key = GetInvocationSignature(invocation);

            if (_cache.Contains(key))
            {
                invocation.ReturnValue = _cache.Get(key);
                return;
            }

            invocation.Proceed();
            var result = invocation.ReturnValue;

            if (result != null)
            {
                _cache.Put(key, result, cacheAttr.Duration);
            }
        }
Ejemplo n.º 6
0
        public override IEnumerable <T> Find(System.Linq.Expressions.Expression <Func <T, bool> > where, params System.Linq.Expressions.Expression <Func <T, object> >[] includeProperties)
        {
            IEnumerable <T> query = _surrogate.Find(where, includeProperties).AsQueryable();

            if (!_cacheProvider.Contains(query))
            {
                CacheItemPolicy policy = WrapPolicy();
                _cacheProvider.Add(query, policy);
            }
            else
            {
                query = _cacheProvider.Get(query);
            }

            return(query);
        }
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            object o   = null;
            string key = GenerateCachekey();

            if (provider.Contains(key))
            {
                outputs = new object[] { };
                WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Cache-Lookup", "NetHttpService Cache Extension v1.0 ");
                CacheEntry entry = provider.GetData <CacheEntry>(key);
                WebOperationContext.Current.OutgoingResponse.ContentType = entry.ContentType;
                o = new MemoryStream(entry.Response);
            }
            else
            {
                o = innerInvoker.Invoke(instance, inputs, out outputs);
                byte[] bytes = GetBytes((Stream)o);
                WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Cache", "MISS from NetHttpService Cache Extension v1.0 ");
                CacheEntry entry = new CacheEntry()
                {
                    ContentType = WebOperationContext.Current.OutgoingResponse.ContentType, Response = bytes
                };
                provider.Add(key, entry);
            }
            return(o);
        }
Ejemplo n.º 8
0
        public void TestUsage()
        {
            _provider.Add("test", "value", DateTimeOffset.MaxValue, "region");

            Assert.That(_provider.Contains("test", "region"), Is.True);
            Assert.That(_provider.Get("test", "region"), Is.EqualTo("value"));
        }
Ejemplo n.º 9
0
        public IDictionary <TId, TEntity> GetCacheFor <TEntity, TId>() where TEntity : IEntity <TId>
        {
            string key = GetEntityCacheKey <TEntity, TId>();

            if (!_rawCache.Contains(key))
            {
                var newCache = ConcurrentDictionaryProvider.Create <TEntity, TId>();
                _rawCache.Put(key, newCache, new SlidingExpirationPolicy(key, newCache, EntityAccessTimeout));
            }
            return(_rawCache.Get <IDictionary <TId, TEntity> >(key));
        }
Ejemplo n.º 10
0
        public async Task <IContent> GetNextFile(CancellationToken token)
        {
            var path = _history.GetNext();

            _history.CurrentIndex++;
            if (!NextFileExists)
            {
                return(_cache.Get(path) as IContent);
            }

            var newNextPath = _history.GetNext();

            if (_cache.Contains(newNextPath))
            {
                return(_cache.Get(path) as IContent);
            }

            bool cachingIsCompleted = false;

            while (!cachingIsCompleted)
            {
                try
                {
                    var newNextContent = await _baseModel.GetContent(newNextPath, token);

                    _cache.Add(newNextPath, newNextContent);
                    cachingIsCompleted = true;
                }
                catch (FileNotFoundException e)
                {
                    _history.Remove(newNextPath);
                    cachingIsCompleted = !NextFileExists;
                    if (!cachingIsCompleted)
                    {
                        newNextPath = _history.GetNext();
                    }
                }
            }
            return(_cache.Get(path) as IContent);
        }
Ejemplo n.º 11
0
 protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     if (_cache.Contains(request))
     {
         return(_cache[request]);
     }
     else
     {
         var response = base.SendAsync(request, cancellationToken);
         _cache[request] = response;
         return(response);
     }
 }
 public void InsertData(object data, string name)
 {
     lock (_memoryCacheLock)
     {
         if (_provider.Contains(name))
         {
             var cacheItem = _provider.Get <string, object>(name);
             ((IList <MemoryData <object> >)cacheItem).Add(new MemoryData <object>
             {
                 Data = data
             });
         }
         else
         {
             _provider.Add(name, new List <MemoryData <object> >
             {
                 new MemoryData <object>
                 {
                     Data = data
                 }
             }, _absoluteExpiry);
         }
     }
 }
Ejemplo n.º 13
0
        public void FillCache(CachedAttribute attribute, IInvocation invocation)
        {
            var cacheKeyGenerator = _cacheKeyGenerators.FirstOrDefault(c => c.GetType() == attribute.CacheKeyGenerator) ?? new DefaultCacheKeyGenerator();
            var cacheKey          = cacheKeyGenerator.GenerateCacheKey(invocation.Method, invocation.Arguments);

            if (_cache.Contains(cacheKey, attribute.CacheRegion))
            {
                invocation.ReturnValue = _cache.Get(cacheKey, attribute.CacheRegion);
            }
            else
            {
                invocation.Proceed();
                var expiration = attribute.TimeoutInMinutes == 0 ? DateTimeOffset.MaxValue : DateTimeOffset.Now.AddMinutes(attribute.TimeoutInMinutes);
                _cache.Add(cacheKey, invocation.ReturnValue, expiration, attribute.CacheRegion);
            }
        }
Ejemplo n.º 14
0
        public int GetProductSaleAmounts(int productId)
        {
            var key = productId.ToString();

            if (_cacheProvider.Contains(key))
            {
                var output = _cacheProvider.Get(key);
                return(Convert.ToInt32(output));
            }
            else
            {
                var productStatements = _repository.GetProductStatements();
                var sum = productStatements.Sum(x => x.Amount);
                _cacheProvider.Put(key, sum.ToString(), 10000);
                return(sum);
            }
        }
Ejemplo n.º 15
0
 public static bool Contains <T>(this ICacheProvider cache, Guid uid) where T : EntityModel, new() =>
 cache.Contains(GetKey <T>(uid));
Ejemplo n.º 16
0
 public bool Contains(string key)
 {
     return(cache.Contains(key));
 }
Ejemplo n.º 17
0
        public static IEnumerable <T> FromCache <T>(this IEnumerable <T> query)
        {
            ICacheProvider provider = Config.Cache.DefaultProvider;

            return(provider.Contains(query) ? provider.Get(query) : query);
        }
        public void Intercept(IInvocation invocation)
        {
            var cacheMethodAttr = GetCacheMethodAttribute(invocation);
            var cacheClassAttr  = GetCacheClassAttribute(invocation);
            // Method attribute has more priority than class attribute
            var cacheAttr = cacheMethodAttr ?? cacheClassAttr;

            // If method has [DoNotCache] attribute, then don't cache it
            var doNotCacheAttribute = GetDontCacheMethodAttribute(invocation);

            if (doNotCacheAttribute != null)
            {
                cacheAttr = null;
            }

            if (cacheAttr == null)
            {
                invocation.Proceed();
                return;
            }

            if (invocation.Method.ReturnType == typeof(void) || invocation.Method.ReturnType == typeof(Task))
            {
                // If attribute is on a method that doesn't have result value than throw exception
                if (cacheMethodAttr != null)
                {
                    throw new InvalidOperationException($"Method \"{invocation.Method.Name}\" with attribute [{nameof(CacheAttribute)}] must return a value, not 'void' or 'Task'.");
                }

                // Otherwise it's on the class - do not intercept
                invocation.Proceed();
                return;
            }

            var key = GetInvocationSignature(invocation);

            if (_cache.Contains(key))
            {
                invocation.ReturnValue = _cache.Get(key);
                return;
            }

            invocation.Proceed();
            var method  = invocation.MethodInvocationTarget;
            var isAsync = method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null;

            if (isAsync && typeof(Task).IsAssignableFrom(method.ReturnType))
            {
                invocation.ReturnValue = InterceptAsync((dynamic)invocation.ReturnValue);
                OnFinish();
            }
            else
            {
                OnFinish();
            }

            void OnFinish()
            {
                var result = invocation.ReturnValue;

                if (result != null)
                {
                    _cache.Put(key, result, cacheAttr.Duration);
                }
            }
        }
Ejemplo n.º 19
0
 public bool Contains(string key)
 {
     return cacheProvider.Contains(key);
 }