コード例 #1
0
        public IActionResult Index()
        {
            // Adding an expiration token allows us to trigger expiration,
            // to ensure that expiration itself is still working.
            var relative = _cache.GetOrAdd(CACHED_ITEM_RELATIVE_KEY, (entry) => {
                // expire immediately
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(1);

                return(new CachedItem
                {
                    Created = DateTime.Now,
                });
            });

            var absolute = _cache.GetOrAdd(CACHED_ITEM_ABSOLUTE_KEY, (entry) => {
                // expire immediately
                entry.AbsoluteExpiration = DateTime.UtcNow + TimeSpan.FromSeconds(1);

                return(new CachedItem
                {
                    Created = DateTime.Now,
                });
            });

            return(View("Index", new CachedItemsResult
            {
                Relative = relative,
                Absolute = absolute,
            }));
        }
コード例 #2
0
        public SiteMapModule(IAppCache appCache)
        {
            cache = appCache;
            cache.GetOrAdd("sitemap1.xml", () => getSiteMap("https://localhost:10623/sitemap1.xml"));
            cache.GetOrAdd("sitemap2.xml", () => getSiteMap("https://localhost:10623/sitemap2.xml"));
            cache.GetOrAdd("sitemap3.xml", () => getSiteMap("https://localhost:10623/sitemap3.xml"));
            cache.GetOrAdd("sitemap.xml", () => getSiteMapIndex("https://localhost:10623/sitemap.xml"));
            var list = new List <string>();

            list.AddRange(new [] { "sitemap1.xml", "sitemap2.xml", "sitemap3.xml", "sitemap.xml" });
            foreach (var item in list)
            {
                Get($"/{item}", async(req, resp) =>
                {
                    if (item.Equals("sitemap.xml"))
                    {
                        var ms           = await cache.Get <Extensions.SiteMapIndex.SiteMapIndex>("sitemap.xml").Parse();
                        resp.ContentType = "application/xml";
                        resp.StatusCode  = 200;
                        await ms.CopyToAsync(resp.Body);
                        return;
                    }

                    var smap         = cache.Get <SiteMap>(item);
                    var ms2          = await smap.Parse();
                    resp.ContentType = "application/xml";
                    resp.StatusCode  = 200;
                    await ms2.CopyToAsync(resp.Body);
                    return;
                });
            }
        }
コード例 #3
0
 public static T AddGetItem(string keyName, T value)
 {
     LogHandler.Info($"Cache - Adding {keyName}");
     return(cache.GetOrAdd(keyName,
                           () => value,
                           DateTimeOffset.Now.AddMinutes(5)));
 }
コード例 #4
0
        private IpAddress GetIpAddress(IpAddress ipAddress)
        {
            var ipAddressCacheKey = $"LoggingService-IPAddresses-{ipAddress.Address}";

            return(_appCache.GetOrAdd(ipAddressCacheKey,
                                      () => _logRepository.GetWithAddIpAddress(ipAddress),
                                      new TimeSpan(0, 10, 0)));
        }
コード例 #5
0
        public IActionResult GetAllUsers()
        {
            Func <ICollection <UserViewModel> > usersGetter = () => _manager.GetAllUsers();

            var usersCached = _cache.GetOrAdd("UsersController.GetUsers", usersGetter, _cacheExpiry);

            return(Ok(usersCached));
        }
コード例 #6
0
        public Profile GetExample()
        {
            Profile ExampleFactory() => _raiderIo.GetExample();

            var profile = _cache.GetOrAdd("exampleProfile", ExampleFactory);

            return(profile);
        }
コード例 #7
0
        public IActionResult GetAllProjects()
        {
            Func <ICollection <ProjectViewModel> > projectsGetter = () => _manager.GetAllProjects();

            var projectsCached = _cache.GetOrAdd("ProjectsController.GetProjects", projectsGetter, _cacheExpiry);

            return(Ok(projectsCached));
        }
コード例 #8
0
        public static async Task <ProxyProcessResult> RunPostProcessors(FHIRResponse response, HttpRequest req, ILogger log, ClaimsPrincipal principal, string res, string id, string hist, string vid)
        {
            ProxyProcessResult rslt = new ProxyProcessResult();

            //Default to server response
            rslt.Response = response;
            //Get Configured PostProcessors
            string pps = System.Environment.GetEnvironmentVariable("POST_PROCESSOR_TYPES");

            if (string.IsNullOrEmpty(pps))
            {
                return(rslt);
            }
            string[] types = pps.Split(",");
            foreach (string cls in types)
            {
                try
                {
                    string         ic = cls;
                    DateTimeOffset os = DateTimeOffset.Now;
                    if (cls.Contains(":"))
                    {
                        string[] x = cls.Split(":");
                        ic = x[0];
                        int exp = DEF_EXP_MINS;
                        int.TryParse(x[1], out exp);
                        os = os.AddMinutes(exp);
                    }
                    else
                    {
                        os = os.AddMinutes(DEF_EXP_MINS);
                    }
                    IProxyPostProcess ip = (IProxyPostProcess)cache.GetOrAdd(cls, () => GetInstance(ic), os);
                    log.LogInformation($"ProxyProcessManager is running {cls} post-process...");
                    rslt = await ip.Process(rslt.Response, req, log, principal, res, id, hist, vid);

                    if (!rslt.Continue)
                    {
                        return(rslt);
                    }
                }
                catch (InvalidCastException ece)
                {
                    log.LogWarning($"{cls} does not seem to implement IProxyPostProcess and will not be executed:{ece.Message}");
                }
                catch (Exception e)
                {
                    log.LogError(e, $"Error trying to instanciate/execute post-process {cls}: {e.Message}");
                    FHIRResponse fhirresp = new FHIRResponse();
                    fhirresp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                    fhirresp.Content    = Utils.genOOErrResponse("internalerror", $"Error trying to instanciate/execute post-process {cls}: {e.Message}");
                    return(new ProxyProcessResult(false, "internalerror", "", fhirresp));
                }
            }
            return(rslt);
        }
コード例 #9
0
        public async Task <IApiResponse> Get([FromQuery] string url)
        {
            if (url is null)
            {
                return(new ErrorResponse {
                    Error = "No url found in query."
                });
            }

            // adds http to url if not present
            url = new UriBuilder(url).Uri.ToString();

            IApiResponse result;
            async Task <IApiResponse> websiteInfoGetter() => await UrlSolverService.GetWebsiteInfo(url);

            // heroku likely won't keep the app awake above 30 minutes
            result = await Cache.GetOrAdd($"websiteInfo-{url}", websiteInfoGetter, TimeSpan.FromMinutes(30));

            if (result is null)
            {
                return(new ErrorResponse {
                    Error = "Couldn't get website info. Try again later."
                });
            }

            return(result);
        }
コード例 #10
0
        public BaseDataResponse <IEnumerable <Guid> > GetMatchingRules(TObjectToMatch objectToMatch, IEnumerable <RulesConfig> rulesConfig)
        {
            var matching = new HashSet <Guid>();

            foreach (var ruleConfig in rulesConfig)
            {
                try
                {
                    var compiledRule = _cache.GetOrAdd($"{GetType().Name}.{ruleConfig.Id}", () =>
                    {
                        return(_compiler.CompileRule <TObjectToMatch>(ruleConfig));
                    });

                    if (compiledRule(objectToMatch))
                    {
                        matching.Add(ruleConfig.Id);
                    }
                }
                catch (Exception exc)
                {
                    return(new BaseDataResponse <IEnumerable <Guid> > {
                        Code = ErrorCode.TechnicalProblem, ErrorDescription = exc.Message, Data = matching
                    });
                }
            }

            return(new BaseDataResponse <IEnumerable <Guid> > {
                Data = matching
            });
        }
コード例 #11
0
        public void GetOrAddOnCore31ReturnsTheCachedItem()
        {
            var cachedResult = sut.GetOrAdd(TestKey, () => new { SomeProperty = "SomeValue" });

            Assert.IsNotNull(cachedResult);
            Assert.AreEqual("SomeValue", cachedResult.SomeProperty);
        }
コード例 #12
0
        public static IList <AvailableFilter> GetAvailableFilters(this IAppCache cache, Func <IList <AvailableFilter> > loader)
        {
            // TODO: Should not be called like this?!
            var list = cache.GetOrAdd(AvailableFiltersKey, loader, DateTimeOffset.UtcNow.AddSeconds(CacheTimeFilter));

            return(list);
        }
コード例 #13
0
 public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory,
                              TimeSpan slidingExpiration)
 {
     return(cache.GetOrAdd(key, addItemFactory,
                           new MemoryCacheEntryOptions {
         SlidingExpiration = slidingExpiration
     }));
 }
コード例 #14
0
ファイル: LazyCacheExtensions.cs プロジェクト: yehuangcn/ccm
 public static List <RegisteredSipDto> GetOrAddRegisteredSips(this IAppCache cache, Func <List <RegisteredSipDto> > registeredSipsLoader)
 {
     using (new TimeMeasurer("GetCachedRegisteredSips from cache."))
     {
         var list = cache.GetOrAdd(RegisteredSipsKey, registeredSipsLoader, DateTimeOffset.UtcNow.AddSeconds(CacheTimeCachedRegisteredSips));
         return(list);
     }
 }
コード例 #15
0
		public Product checkCache(string productId)
		{
			Func<Product> loadedProduct = () => LoadProduct(productId);

			Product cachedResult = cache.GetOrAdd(productId, loadedProduct, DateTimeOffset.UtcNow.AddMinutes(15));

			return cachedResult;
		}
コード例 #16
0
        public async Task <Summary> GetSummaryAsync(int stationId)
        {
            var result = await _cache.GetOrAdd($"summary-{stationId}",
                                               () => GenerateSummary(stationId),
                                               TimeSpan.FromMinutes(10));

            return(result);
        }
コード例 #17
0
ファイル: DbTimeController.cs プロジェクト: yply/LazyCache
        public DbTimeEntity Get()
        {
            Func <DbTimeEntity> actionThatWeWantToCache = () => dbContext.GeDbTime();

            var cachedDatabaseTime = cache.GetOrAdd(cacheKey, actionThatWeWantToCache);

            return(cachedDatabaseTime);
        }
コード例 #18
0
 public FroniusClearCommandHandler(
     ILogger logger,
     IAppCache cache)
 {
     _logger = logger;
     _cache  = cache;
     _cache.GetOrAdd(SolarPowerCache.CacheKey, () => new ConcurrentDictionary <long, string>());
 }
コード例 #19
0
ファイル: HomeController.cs プロジェクト: dsjlee/Proto
        public JsonResult Cache()
        {
            var list = _cache.GetOrAdd("BroadcastMessage", () => new List <BroadcastMessage>());

            list.Add(new BroadcastMessage {
                Message = "hello"
            });
            return(Json(list, JsonRequestBehavior.AllowGet));
        }
コード例 #20
0
        public byte[] GetArbitraryBytes(FileSize bytes)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }

            return(cache.GetOrAdd(bytes.ToString(), () => Enumerable.Range(0, (int)bytes).Select(i => (byte)(i % 251 + 1)).ToArray()));
        }
コード例 #21
0
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory, DateTimeOffset expires, ExpirationMode mode)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            switch (mode)
            {
            case ExpirationMode.LazyExpiration:
                return(cache.GetOrAdd(key, addItemFactory, new MemoryCacheEntryOptions {
                    AbsoluteExpiration = expires
                }));

            default:
                return(cache.GetOrAdd(key, addItemFactory, new LazyCacheEntryOptions().SetAbsoluteExpiration(expires, mode)));
            }
        }
コード例 #22
0
        public IActionResult GetTicket(string ticketId)
        {
            Func <TicketViewModel> ticketGetter = () => _manager.GetTicket(ticketId);

            var cacheExpiry = new TimeSpan(0, 0, 1);

            TicketViewModel ticketVMCached = _cache.GetOrAdd(
                "TicketsController.GetTicket." + ticketId,
                ticketGetter,
                cacheExpiry);

            if (ticketVMCached == null)
            {
                return(NotFound($"Ticket with id '{ticketId}' could not be found."));
            }

            return(Ok(ticketVMCached));
        }
コード例 #23
0
        public async Task <CodecInformation> GetCodecInformationBySipAddress(string sipAddress)
        {
            var ci = await _cache.GetOrAdd(
                CacheKeys.CodecInformation(sipAddress),
                () => _ccmRepository.GetCodecInformation(sipAddress),
                DateTime.Now.AddSeconds(_reloadIntervalInSeconds));

            return(ci);
        }
コード例 #24
0
        /// <summary>
        /// Add item to cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="addItemFactory"></param>
        /// <returns></returns>
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            return(cache.GetOrAdd(key, addItemFactory, cache.DefaultCachePolicy.BuildOptions()));
        }
コード例 #25
0
        public void CanCreateCache()
        {
            IKernel   kernel = new StandardKernel(new LazyCacheModule());
            IAppCache cache  = kernel.Get <IAppCache>();

            var cached = cache.GetOrAdd("some-key", () => new object());

            Assert.NotNull(cached);
        }
コード例 #26
0
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory,
                                     MemoryCacheEntryOptions policy)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            return(cache.GetOrAdd(key, _ => addItemFactory(), policy));
        }
コード例 #27
0
        public Dictionary <(string, string), Event> GetEvents(DateTime date)
        {
            var cacheKey = $"Events-{date:MMdd}";

            return(_cache.GetOrAdd(cacheKey, () =>
            {
                var events = Find(x => x.Date == date).ToList();

                return events.Any() ? events.ToDictionary(x => (x.StockCode, x.EventType), x => x) : null;
            }, _stockMarketStatusRepository.NextClosingDateTime()));
コード例 #28
0
        public virtual void GetOrAdd_Guid_ReturnsExpectedResult(bool withCacheEntryOptions)
        {
            var cacheEntryKey     = Fixture.Create <string>();
            var expectedResult    = Fixture.Create <Guid>();
            var cacheEntryOptions = Fixture.Create <MemoryCacheEntryOptions>();

            var actualResult = withCacheEntryOptions
                ? CachingService.GetOrAdd(cacheEntryKey, () => expectedResult, cacheEntryOptions)
                : CachingService.GetOrAdd(cacheEntryKey, () => expectedResult);

            Assert.That(actualResult, Is.EqualTo(expectedResult));
        }
コード例 #29
0
        // GET: Products
        public async Task <IActionResult> Index()
        {
            // define a func to get the products but do not Execute() it
            Func <IEnumerable <Product> > productGetter = () => _context.Product.ToList();

            // get the results from the cache based on a unique key, or
            // execute the func and cache the results
            var productsWithCaching = _cache.GetOrAdd("ProductsController.Get", productGetter);

            return(View(productsWithCaching));
        }
コード例 #30
0
        /// <summary>
        /// Add item to cache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="addItemFactory"></param>
        /// <param name="expires"></param>
        /// <returns></returns>
        public static T GetOrAdd <T>(this IAppCache cache, string key, Func <T> addItemFactory, DateTimeOffset expires)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            return(cache.GetOrAdd(key, addItemFactory, new MemoryCacheEntryOptions {
                AbsoluteExpiration = expires
            }));
        }