public void Set(string route, OutputCacheResponseEntry entry, HttpContext context)
        {
            if (!context.IsOutputCachingEnabled(out OutputCacheProfile profile))
            {
                return;
            }

            var env = (IHostingEnvironment)context.RequestServices.GetService(typeof(IHostingEnvironment));

            var options = new MemoryCacheEntryOptions();

            if (profile.UseAbsoluteExpiration)
            {
                options.SetAbsoluteExpiration(TimeSpan.FromSeconds(profile.Duration));
            }
            else
            {
                options.SetSlidingExpiration(TimeSpan.FromSeconds(profile.Duration));
            }

            foreach (string globs in profile.FileDependencies)
            {
                options.AddExpirationToken(env.ContentRootFileProvider.Watch(globs));
            }

            string cleanRoute = NormalizeRoute(route);

            _cache.Set(cleanRoute, entry, options);
        }
Exemplo n.º 2
0
        private ViewLocationCacheResult LocatePageFromPath(string executingFilePath, string pagePath, bool isMainPage)
        {
            var applicationRelativePath = GetAbsolutePath(executingFilePath, pagePath);
            var cacheKey = new ViewLocationCacheKey(applicationRelativePath, isMainPage);

            if (!ViewLookupCache.TryGetValue(cacheKey, out ViewLocationCacheResult cacheResult))
            {
                var expirationTokens = new HashSet <IChangeToken>();
                cacheResult = CreateCacheResult(expirationTokens, applicationRelativePath, isMainPage);

                var cacheEntryOptions = new MemoryCacheEntryOptions();
                cacheEntryOptions.SetSlidingExpiration(_cacheExpirationDuration);
                foreach (var expirationToken in expirationTokens)
                {
                    cacheEntryOptions.AddExpirationToken(expirationToken);
                }

                // No views were found at the specified location. Create a not found result.
                if (cacheResult == null)
                {
                    cacheResult = new ViewLocationCacheResult(new[] { applicationRelativePath });
                }

                cacheResult = ViewLookupCache.Set(
                    cacheKey,
                    cacheResult,
                    cacheEntryOptions);
            }

            return(cacheResult);
        }
        /// <summary>
        /// sets the cache entry T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expirationInMinutes"></param>
        /// <returns></returns>
        public T Set <T>(object key, T value, int expirationInMinutes = 60)
        {
            var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal).SetAbsoluteExpiration(TimeSpan.FromMinutes(expirationInMinutes));

            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
            _memoryCache.Set(key, value, options);
            return(value);
        }
Exemplo n.º 4
0
        private MemoryCacheEntryOptions GetMemoryCacheEntryOptions()
        {
            var options = new MemoryCacheEntryOptions();

            options.AddExpirationToken(new CancellationChangeToken(CancellationToken.None));

            return(options);
        }
        private TItem Set <TItem>(IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options, CancellationTokenSource token)
        {
            MemoryCacheEntryOptions opt = options ?? new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal);

            opt.AddExpirationToken(new CancellationChangeToken(token.Token));

            return(cache.Set(key, value, opt));
        }
Exemplo n.º 6
0
        public void Set <T>(string key, T value)
        {
            var options = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(this._apiSetting.Interval));

            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));

            _memoryCache.Set(key, value);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Prepare cache entry options for the passed key
        /// </summary>
        /// <returns>Cache entry options</returns>
        private MemoryCacheEntryOptions PrepareEntryOptions(string key, int cacheTime)
        {
            //set expiration time for the passed cache key
            var options = new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(cacheTime)
            };

            //add tokens to clear cache entries
            options.AddExpirationToken(new CancellationChangeToken(_clearToken.Token));

            var tokenSource = _keys.GetOrAdd(key, new CancellationTokenSource());

            options.AddExpirationToken(new CancellationChangeToken(tokenSource.Token));

            return(options);
        }
Exemplo n.º 8
0
        private MemoryCacheEntryOptions GetMemoryCacheEntryOptions(string relativePath)
        {
            var options = new MemoryCacheEntryOptions();

            options.AddExpirationToken(_fileProvider.Watch(relativePath));

            return(options);
        }
Exemplo n.º 9
0
        private void UpdateReset(string name)
        {
            var mo = new MemoryCacheEntryOptions();

            mo.RegisterPostEvictionCallback(this.PostEvictionCallback);
            mo.AddExpirationToken(
                new CancellationChangeToken(new CancellationTokenSource(ResetCacheTimeout).Token));
            this.cache.Set($"feeds:reset:<{name}>", DateTime.Now, mo);
        }
    /* other method and ctor removed for brevity */
    public T Set <T>(object key, T value)
    {
        /* some other code removed for brevity */
        var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal).SetAbsoluteExpiration(typeExpiration);

        options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
        _innerCache.Set(CreateKey(type, key), value, options);
        return(value);
    }
Exemplo n.º 11
0
        /// <summary>
        /// Prepare cache entry options for the passed key
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <returns>Cache entry options</returns>
        private MemoryCacheEntryOptions PrepareEntryOptions(CacheKey key)
        {
            //set expiration time for the passed cache key
            var options = new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(key.CacheTime)
            };

            //add tokens to clear cache entries
            options.AddExpirationToken(new CancellationChangeToken(_clearToken.Token));
            foreach (var keyPrefix in key.Prefixes.ToList())
            {
                var tokenSource = _prefixes.GetOrAdd(keyPrefix, new CancellationTokenSource());
                options.AddExpirationToken(new CancellationChangeToken(tokenSource.Token));
            }

            return(options);
        }
Exemplo n.º 12
0
        public override void Set(DocumentInfo info)
        {
            var options = new MemoryCacheEntryOptions()
                          .SetPriority(CacheItemPriority.NeverRemove);

            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));

            Cache.Set(CacheOf(info), Serializer.Serialize(info), options);
        }
Exemplo n.º 13
0
 public void SetData <T>(string cacheName, string cacheKey, T data, MemoryCacheEntryOptions options)
 {
     if (!string.IsNullOrWhiteSpace(cacheName) && options != null)
     {
         var cts = CacheTokenManager.Instance.GetCacheToken(cacheName);
         options.AddExpirationToken(new CancellationChangeToken(cts.Token));
     }
     _memoryCache.Set <T>(cacheKey, data, options);
 }
Exemplo n.º 14
0
    private ViewLocationCacheResult OnCacheMiss(
        ViewLocationExpanderContext expanderContext,
        ViewLocationCacheKey cacheKey)
    {
        var viewLocations = GetViewLocationFormats(expanderContext);

        var expanders = _options.ViewLocationExpanders;
        // Read interface .Count once rather than per iteration
        var expandersCount = expanders.Count;

        for (var i = 0; i < expandersCount; i++)
        {
            viewLocations = expanders[i].ExpandViewLocations(expanderContext, viewLocations);
        }

        ViewLocationCacheResult?cacheResult = null;
        var searchedLocations = new List <string>();
        var expirationTokens  = new HashSet <IChangeToken>();

        foreach (var location in viewLocations)
        {
            var path = string.Format(
                CultureInfo.InvariantCulture,
                location,
                expanderContext.ViewName,
                expanderContext.ControllerName,
                expanderContext.AreaName);

            path = ViewEnginePath.ResolvePath(path);

            cacheResult = CreateCacheResult(expirationTokens, path, expanderContext.IsMainPage);
            if (cacheResult != null)
            {
                break;
            }

            searchedLocations.Add(path);
        }

        // No views were found at the specified location. Create a not found result.
        if (cacheResult == null)
        {
            cacheResult = new ViewLocationCacheResult(searchedLocations);
        }

        var cacheEntryOptions = new MemoryCacheEntryOptions();

        cacheEntryOptions.SetSlidingExpiration(_cacheExpirationDuration);
        foreach (var expirationToken in expirationTokens)
        {
            cacheEntryOptions.AddExpirationToken(expirationToken);
        }

        ViewLookupCache.Set(cacheKey, cacheResult, cacheEntryOptions);
        return(cacheResult);
    }
Exemplo n.º 15
0
        public void Set(string key, object value, ICacheEntryOptions options)
        {
            var _options = new MemoryCacheEntryOptions()
            {
                AbsoluteExpiration = options.AbsoluteExpiration, AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow, SlidingExpiration = options.SlidingExpiration
            };

            _options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
            _client.Set(key, value, _options);
            _keys.Add(key);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Adds string value to memory cache.
        /// </summary>
        protected void AddToCache(string cacheKey, string value, IFileProvider fileProvider, params string[] files)
        {
            var cacheOptions = new MemoryCacheEntryOptions();

            foreach (string file in files)
            {
                cacheOptions.AddExpirationToken(fileProvider.Watch(file));
            }

            Cache.Set(cacheKey, value, cacheOptions);
        }
Exemplo n.º 17
0
        public void Set(string key, CultureInfo culture, string value)
        {
            key = GetCacheKey(key, culture);
            var options = new MemoryCacheEntryOptions()
                          .SetPriority(CacheItemPriority.Normal)
                          .SetSlidingExpiration(_settings.CacheExpirationOffset);

            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));

            _innerCache.Set(key, value, options);
        }
Exemplo n.º 18
0
        private IReadOnlyList <string> ExpandGlobbedUrl(string include, string exclude)
        {
            if (string.IsNullOrEmpty(include))
            {
                return(Array.Empty <string>());
            }

            var cacheKey = new GlobbingUrlKey(include, exclude);

            if (Cache.TryGetValue(cacheKey, out List <string> files))
            {
                return(files);
            }

            var includeTokenizer  = new StringTokenizer(include, PatternSeparator);
            var includeEnumerator = includeTokenizer.GetEnumerator();

            if (!includeEnumerator.MoveNext())
            {
                return(Array.Empty <string>());
            }

            var options = new MemoryCacheEntryOptions();
            var trimmedIncludePatterns = new List <string>();

            foreach (var includePattern in includeTokenizer)
            {
                var changeToken = FileProvider.Watch(includePattern.Value);
                options.AddExpirationToken(changeToken);
                trimmedIncludePatterns.Add(NormalizePath(includePattern));
            }
            var matcher = MatcherBuilder != null?MatcherBuilder() : new Matcher();

            matcher.AddIncludePatterns(trimmedIncludePatterns);

            if (!string.IsNullOrWhiteSpace(exclude))
            {
                var excludeTokenizer       = new StringTokenizer(exclude, PatternSeparator);
                var trimmedExcludePatterns = new List <string>();
                foreach (var excludePattern in excludeTokenizer)
                {
                    trimmedExcludePatterns.Add(NormalizePath(excludePattern));
                }
                matcher.AddExcludePatterns(trimmedExcludePatterns);
            }

            var(matchedUrls, sizeInBytes) = FindFiles(matcher);
            options.SetSize(sizeInBytes);

            return(Cache.Set(
                       cacheKey,
                       matchedUrls,
                       options));
        }
Exemplo n.º 19
0
        public override void Set(DocumentMeta meta, int expire)
        {
            var expiration = TimeSpan.FromMinutes(expire);
            var options    = new MemoryCacheEntryOptions()
                             .SetPriority(CacheItemPriority.Normal)
                             .SetAbsoluteExpiration(expiration);

            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));

            Cache.Set(CacheOf(meta), Serializer.Serialize(meta), options);
        }
        private ViewLocationCacheResult OnCacheMiss(
            ViewLocationExpanderContext expanderContext,
            ViewLocationCacheKey cacheKey)
        {
            // Only use the area view location formats if we have an area token.
            IEnumerable <string> viewLocations = !string.IsNullOrEmpty(expanderContext.AreaName) ?
                                                 AreaViewLocationFormats :
                                                 ViewLocationFormats;

            for (var i = 0; i < _options.ViewLocationExpanders.Count; i++)
            {
                viewLocations = _options.ViewLocationExpanders[i].ExpandViewLocations(expanderContext, viewLocations);
            }

            ViewLocationCacheResult cacheResult = null;
            var searchedLocations = new List <string>();
            var expirationTokens  = new HashSet <IChangeToken>();
            var template          = expanderContext.ActionContext.HttpContext.RequestServices.GetService <TemplateManager>();

            foreach (var location in viewLocations)
            {
                var path = string.Format(
                    CultureInfo.InvariantCulture,
                    location,
                    expanderContext.ViewName,
                    expanderContext.ControllerName,
                    template.Current.Identifier,
                    expanderContext.AreaName);

                cacheResult = CreateCacheResult(expirationTokens, path, expanderContext.IsMainPage);
                if (cacheResult != null)
                {
                    break;
                }

                searchedLocations.Add(path);
            }

            // No views were found at the specified location. Create a not found result.
            if (cacheResult == null)
            {
                cacheResult = new ViewLocationCacheResult(searchedLocations);
            }

            var cacheEntryOptions = new MemoryCacheEntryOptions();

            cacheEntryOptions.SetSlidingExpiration(_cacheExpirationDuration);
            foreach (var expirationToken in expirationTokens)
            {
                cacheEntryOptions.AddExpirationToken(expirationToken);
            }

            return(ViewLookupCache.Set <ViewLocationCacheResult>(cacheKey, cacheResult, cacheEntryOptions));
        }
Exemplo n.º 21
0
        public void Set <TCachedObject>(string key, TCachedObject value, uint secondsCacheTime)
        {
            var options = new MemoryCacheEntryOptions()
                          .SetPriority(CacheItemPriority.Normal)
                          .SetAbsoluteExpiration(TimeSpan.FromSeconds(secondsCacheTime));

            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));

            _memoryCache.Set(key, value, options);
            CacheKeys.Add(key);
        }
Exemplo n.º 22
0
        public override void Set <T>(DocumentQuery query, T data)
        {
            var expiration = TimeSpan.FromMinutes(query.CacheOf.Expire);
            var options    = new MemoryCacheEntryOptions()
                             .SetPriority(CacheItemPriority.Normal)
                             .SetAbsoluteExpiration(expiration);

            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));

            Cache.Set(CacheOf(query), data, options);
        }
Exemplo n.º 23
0
        public void Set(string key, object value, int timeInSeconds)
        {
            if (timeInSeconds <= 0)
            {
                return;
            }
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetSlidingExpiration(TimeSpan.FromSeconds(timeInSeconds));

            cacheEntryOptions.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
            _memoryCache.Set(key, value, cacheEntryOptions);
        }
Exemplo n.º 24
0
        public async Task CacheBasicBehaviorAsync()
        {
            var invoked = 0;

            string ExpensiveComputation(string argument)
            {
                invoked++;
                return("Hello " + argument);
            }

            using var cache      = new MemoryCache(new MemoryCacheOptions());
            using var expireKey1 = new CancellationTokenSource();

            var options = new MemoryCacheEntryOptions {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10)
            };

            options.AddExpirationToken(new CancellationChangeToken(expireKey1.Token));
            var result0 = await cache.AtomicGetOrCreateAsync(
                "key1",
                options,
                () => Task.FromResult(ExpensiveComputation("World!")));

            var result1 = await cache.AtomicGetOrCreateAsync(
                "key2",
                new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
                () => Task.FromResult(ExpensiveComputation("Loving Wife!")));

            var result2 = await cache.AtomicGetOrCreateAsync(
                "key1",
                new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
                () => Task.FromResult(ExpensiveComputation("World!")));

            Assert.Equal(result0, result2);
            Assert.NotEqual(result0, result1);
            Assert.Equal(2, invoked);

            // Make sure key1 expired.
            expireKey1.Cancel();
            var result3 = await cache.AtomicGetOrCreateAsync(
                "key1",
                new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
                () => Task.FromResult(ExpensiveComputation("Foo!")));

            var result4 = await cache.AtomicGetOrCreateAsync(
                "key2",
                new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(10) },
                () => Task.FromResult(ExpensiveComputation("Bar!")));

            Assert.Equal(result1, result4);
            Assert.NotEqual(result0, result3);
            Assert.Equal(3, invoked);
        }
Exemplo n.º 25
0
        protected T GetCached <T>(Func <T> create, string key = null)
        {
            var options = new MemoryCacheEntryOptions();

            options.SetSlidingExpiration(TimeSpan.FromMinutes(60));
            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));
            return(memoryCache.GetOrCreate(key ?? typeof(T).ToString(), entry =>
            {
                try { entry.SetOptions(options); } catch { }//moq catch
                return create.Invoke();
            }));
        }
Exemplo n.º 26
0
        private async Task <User> PrepareUserResultAsync(MemoryCacheEntryOptions options, AutoRestClients.PlatformModuleApi.Models.ApplicationUserExtended userDto)
        {
            if (userDto != null)
            {
                var user = userDto.ToUser();
                var orderSearchResult = await _orderModule.SearchAsync(new CustomerOrderSearchCriteria()
                {
                    CustomerId = user.Id,
                    Take       = 0,
                    Skip       = 0,
                });

                user.IsFirstTimeBuyer = orderSearchResult.TotalCount == 0;

                options.AddExpirationToken(new PollingApiUserChangeToken(_platformSecurityApi, _options.ChangesPollingInterval));
                options.AddExpirationToken(SecurityCacheRegion.CreateChangeToken(userDto.Id));

                return(user);
            }
            return(null);
        }
Exemplo n.º 27
0
 /// <summary>从文件中获取缓存,若文件变更,自动刷新缓存(未测试)</summary>
 public static string GetFileCache(string fileName)
 {
     if (_memory.TryGetValue(fileName, out string txt))
     {
         var fileInfo = new FileInfo(fileName);
         txt = File.ReadAllText(fileName);
         var cacheEntityOps = new MemoryCacheEntryOptions();
         cacheEntityOps.AddExpirationToken(new PollingFileChangeToken(fileInfo));                                             // 监控文件变化
         cacheEntityOps.RegisterPostEvictionCallback((key, value, reason, state) => { Console.WriteLine($"文件 {key} 改动了"); }); // 缓存失效时处理
         _memory.Set(fileInfo.Name, txt, cacheEntityOps);
     }
     return(txt);
 }
Exemplo n.º 28
0
 public static void SetCache(string CacheKey, object objObject, CacheDependency depend)
 {
     if (objObject == null)
     {
         _memoryCache.Remove(CacheKey);
     }
     else
     {
         MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions();
         cacheEntityOps.AddExpirationToken(depend);
         _memoryCache.Set(CacheKey, objObject, cacheEntityOps);
     }
 }
Exemplo n.º 29
0
        private MemoryCacheEntryOptions GetOptions(TimeSpan?expires)
        {
            var options = new MemoryCacheEntryOptions();

            options.SetPriority(CacheItemPriority.Normal);
            options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token));

            if (expires != null)
            {
                options.SetAbsoluteExpiration(expires.Value);
            }

            return(options);
        }
Exemplo n.º 30
0
    private MemoryCacheEntryOptions CacheOptions(int size, double expireInSeconds, bool addExpitationToken = false)
    {
        var cacheOptions = new MemoryCacheEntryOptions
        {
            Size = size,
            AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(expireInSeconds)
        };

        if (addExpitationToken)
        {
            cacheOptions.AddExpirationToken(new CancellationChangeToken(TipChangeCancellationTokenSource.Token));
        }
        return(cacheOptions);
    }
Exemplo n.º 31
0
        private MemoryCacheEntryOptions GetMemoryCacheEntryOptions(string relativePath)
        {
            var options = new MemoryCacheEntryOptions();
            options.AddExpirationToken(_fileProvider.Watch(relativePath));

            var viewImportsPaths = ViewHierarchyUtility.GetViewImportsLocations(relativePath);
            foreach (var location in viewImportsPaths)
            {
                options.AddExpirationToken(_fileProvider.Watch(location));
            }

            return options;
        }
Exemplo n.º 32
0
        private CompilerCacheResult CreateCacheEntry(
            string normalizedPath,
            Func<RelativeFileInfo, CompilationResult> compile)
        {
            CompilerCacheResult cacheResult;
            var fileInfo = _fileProvider.GetFileInfo(normalizedPath);
            MemoryCacheEntryOptions cacheEntryOptions;
            CompilerCacheResult cacheResultToCache;
            if (!fileInfo.Exists)
            {
                cacheResultToCache = CompilerCacheResult.FileNotFound;
                cacheResult = CompilerCacheResult.FileNotFound;

                cacheEntryOptions = new MemoryCacheEntryOptions();
                cacheEntryOptions.AddExpirationToken(_fileProvider.Watch(normalizedPath));
            }
            else
            {
                var relativeFileInfo = new RelativeFileInfo(fileInfo, normalizedPath);
                var compilationResult = compile(relativeFileInfo).EnsureSuccessful();
                cacheEntryOptions = GetMemoryCacheEntryOptions(normalizedPath);

                // By default the CompilationResult returned by IRoslynCompiler is an instance of
                // UncachedCompilationResult. This type has the generated code as a string property and do not want
                // to cache it. We'll instead cache the unwrapped result.
                cacheResultToCache = new CompilerCacheResult(
                    CompilationResult.Successful(compilationResult.CompiledType));
                cacheResult = new CompilerCacheResult(compilationResult);
            }

            _cache.Set(normalizedPath, cacheResultToCache, cacheEntryOptions);
            return cacheResult;
        }
Exemplo n.º 33
0
        private static IMemoryCache MakeCache(object result = null)
        {
            var cache = new Mock<IMemoryCache>();
            cache.CallBase = true;
            cache.Setup(c => c.TryGetValue(It.IsAny<string>(), out result))
                .Returns(result != null);

            var cacheEntryOptions = new MemoryCacheEntryOptions();
            cacheEntryOptions.AddExpirationToken(Mock.Of<IChangeToken>());
            cache
                .Setup(
                    c => c.Set(
                        /*key*/ It.IsAny<string>(),
                        /*value*/ It.IsAny<object>(),
                        /*options*/ cacheEntryOptions))
                .Returns(result);
            return cache.Object;
        }