/// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="value">缓存Value</param>
        /// <param name="expiresIn">缓存时间</param>
        /// <returns></returns>
        public bool Set(string key, object value, int expiresIn = 0)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (expiresIn > 0)
            {
                _memoryCache.Set(key, value,
                                 new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(120))
                                 .SetAbsoluteExpiration(TimeSpan.FromMinutes(expiresIn)));
            }
            else
            {
                _memoryCache.Set(key, value,
                                 new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(120))
                                 .SetAbsoluteExpiration(TimeSpan.FromMinutes(1440)));
            }

            return(Exists(key));
        }
예제 #2
0
        public void RemoveField(string key, string field)
        {
            Assert.NotNull(key, nameof(key));
            Assert.NotNull(field, nameof(field));

            var dicts = _internal.Get <Dictionary <string, object> >(key);

            if (dicts != null && dicts.ContainsKey(field))
            {
                dicts.Remove(field);
                _internal.Set(key, dicts);
            }
        }
예제 #3
0
        protected override Task SetAsync <T>(
            CacheKey cacheKey,
            DateTimeOffset absoluteExpiration,
            T value,
            CancellationToken cancellationToken)
        {
            _memoryCache.Set(
                cacheKey.Value,
                value,
                absoluteExpiration);

            return(Task.FromResult(0));
        }
예제 #4
0
        public static void Main(string[] args)
        {
            // Runs several concurrent threads that access an item that periodically expires and is re-created.
            MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            string key = "MyKey";

            var options = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMilliseconds(50));

            var tasks = new List<Task>();
            for (int threads = 0; threads < 100; threads++)
            {
                var task = Task.Run(() =>
                {
                    for (int i = 0; i < 110000; i++)
                    {
                        object value;
                        if(!cache.TryGetValue(key, out value))
                        {
                            // Fake expensive object creation.
                            for (int j = 0; j < 1000000; j++)
                            {
                            }

                            cache.Set(key, new object(), options);
                        }
                    }
                });
                tasks.Add(task);
            }

            Console.WriteLine("Running");
            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("Done");
        }
예제 #5
0
        public async Task <IPage> GetOrCreate(object key, Func <Task <IPage> > createItem)
        {
            IPage cacheEntry;

            if (!m_Cache.TryGetValue(key, out cacheEntry))
            {
                SemaphoreSlim mylock = m_Locks.GetOrAdd(key, k => new SemaphoreSlim(1, 1));

                await mylock.WaitAsync();

                try
                {
                    if (!m_Cache.TryGetValue(key, out cacheEntry))
                    {
                        cacheEntry = await createItem();

                        m_Cache.Set(key, cacheEntry);
                    }
                }
                finally
                {
                    mylock.Release();
                }
            }
            return(cacheEntry);
        }
예제 #6
0
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="value">缓存Value</param>
        /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
        /// <param name="expiressAbsoulte">绝对过期时长</param>
        /// <returns></returns>
        public static bool Set(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            Cache.Set(key, value,
                      new MemoryCacheEntryOptions().SetSlidingExpiration(expiresSliding)
                      .SetAbsoluteExpiration(expiressAbsoulte));
            return(Exists(key));
        }
예제 #7
0
 /// <inheritdoc />
 public override async Task SetAsync <T>(string key, T value, TimeSpan?slidingExpireTime = null)
 {
     if (value == null)
     {
         throw new Exception("Can not insert null values to the cache!");
     }
     _memoryCache.Set(key, value, slidingExpireTime ?? _cacheOptions.DefaultSlidingExpireTime);
     await Task.FromResult(0);
 }
예제 #8
0
        public string getLocalPathForURL(string url, string name)
        {
            string localPath = null;

            if (memCache.TryGetValue(name, out localPath))
            {
                return(Path.Combine(specificFolder, localPath));
            }
            memCache.Set(name, name);

            return(null);
        }
예제 #9
0
        public void TestInitialize()
        {
            cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
            List <string>  fpListOfKeys = new List <string>();
            List <Segment> segments     = new List <Segment>();
            Segment        segment      = new Segment {
                Latitude = 30, Longitude = 60, TimespanSeconds = 120
            };

            segments.Add(segment);
            testFlightPlan = new FlightPlan
            {
                FlightPlanId    = "123",
                InitialLocation = new FlightPlan.Location {
                    Longitude = 0, Latitude = 0, DateTime = DateTime.Parse("2020-05-30T12:00:00Z")
                },
                Segments = segments
            };
            fpListOfKeys.Add("123");
            cache.Set("flightListKeys", fpListOfKeys);
            cache.Set("123", testFlightPlan);
        }
예제 #10
0
        public override void Set(string key, object value, TimeSpan?slidingExpireTime = null, TimeSpan?absoluteExpireTime = null)
        {
            if (value == null)
            {
                throw new BaseException("Can not insert null values to the cache!");
            }

            if (absoluteExpireTime != null)
            {
                _memoryCache.Set(key, value, DateTimeOffset.Now.Add(absoluteExpireTime.Value));
            }
            else if (slidingExpireTime != null)
            {
                _memoryCache.Set(key, value, slidingExpireTime.Value);
            }
            else if (DefaultAbsoluteExpireTime != null)
            {
                _memoryCache.Set(key, value, DateTimeOffset.Now.Add(DefaultAbsoluteExpireTime.Value));
            }
            else
            {
                _memoryCache.Set(key, value, DefaultSlidingExpireTime);
            }
        }
예제 #11
0
        public void TestMemoryObject()
        {
            var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());

            cache.Set("user", new User {
                Name = "Foo"
            });
            var f = cache.Get <User>("user");

            Assert.Equal("Foo", f.Name);

            f.Name = "Bar";
            var b = cache.Get <User>("user");

            Assert.Equal("Bar", b.Name);
        }
예제 #12
0
        /// <summary>
        /// 获取存储过程的参数(注意:要链接数据库,高耗费资源的操作)
        /// </summary>
        /// <param name="procedureName"></param>
        /// <param name="dbProviderFactory"></param>
        /// <returns></returns>
        protected virtual DbParameterCollection GetStoredProcedureParameters(string procedureName, string connectionString, DbProviderFactory dbProviderFactory)
        {
            if (string.IsNullOrEmpty(procedureName))
            {
                throw new ArgumentNullException("procedureName");
            }
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("connectionString");
            }
            if (dbProviderFactory == null)
            {
                throw new ArgumentNullException("dbProviderFactory");
            }
            string cacheKey = $"DatabaseProcedureParameters_{procedureName}";
            DbParameterCollection cachedDbParameterCollection = memoryCache.Get <DbParameterCollection>(cacheKey);

            if (cachedDbParameterCollection == null)
            {
                DbCommand dbCommand = dbProviderFactory.CreateCommand();
                dbCommand.CommandType = CommandType.StoredProcedure;
                dbCommand.CommandText = procedureName;
                using (DbConnection connection = dbProviderFactory.CreateConnection())
                {
                    connection.ConnectionString = connectionString;
                    connection.Open();
                    dbCommand.Connection = connection;
                    DeriveParameters(dbCommand);
                    connection.Close();
                }
                cachedDbParameterCollection = dbCommand.Parameters;
#warning 暂时写死5分钟缓存过期
                memoryCache.Set(cacheKey, cachedDbParameterCollection, new MemoryCacheEntryOptions()
                {
                    SlidingExpiration = TimeSpan.FromMinutes(5)
                });
            }
            return(cachedDbParameterCollection);
        }
예제 #13
0
    public TItem GetOrCreate(object key, Func <TItem> createItem)
    {
        bool isCache = true;

        if (!_cache.TryGetValue(key, out TItem cacheEntry))// Look for cache key.
        {
            SemaphoreSlim mylock = _locks.GetOrAdd(key, k => new SemaphoreSlim(1, 1));

            mylock.Wait();
            try
            {
                if (!_cache.TryGetValue(key, out cacheEntry))
                {
                    // Key not in cache, so get data.
                    isCache    = false;
                    cacheEntry = createItem();
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                                            .SetSize(1) //Size amount
                                                        //Priority on removing when reaching size limit (memory pressure)
                                            .SetPriority(Microsoft.Extensions.Caching.Memory.CacheItemPriority.Low)
                                                        // Keep in cache for this time, reset time if accessed.
                                            .SetSlidingExpiration(TimeSpan.FromSeconds(4))
                                                        // Remove from cache after this time, regardless of sliding expiration
                                            .SetAbsoluteExpiration(TimeSpan.FromSeconds(10));

                    _cache.Set(key, cacheEntry, cacheEntryOptions);
                }
            }
            finally
            {
                mylock.Release();
            }
        }
        if (isCache)
        {
            logger.Info($"Cache : {cacheEntry.ToString()}");
        }
        return(cacheEntry);
    }
예제 #14
0
        public void CheckFlights()
        {
            // Create new cache memory and it's keys.
            var cache = new Microsoft.Extensions.Caching.Memory.
                        MemoryCache(new MemoryCacheOptions());
            List <Server> serversList            = new List <Server>();
            List <string> keysList               = new List <string>();
            Dictionary <string, string> serverOf = new Dictionary <string, string>();

            cache.Set("servers", serversList);
            cache.Set("keys", keysList);
            cache.Set("serverOfIds", serverOf);

            // Check Post method of flight plans.
            FlightPlanController fpController = new FlightPlanController(cache)
            {
                ControllerContext = new ControllerContext
                {
                    HttpContext = new DefaultHttpContext()
                }
            };
            FlightPlan fp = new FlightPlan();

            // Fill flightPlan fields for posting it.
            fp.Passengers                = 200;
            fp.CompanyName               = "SwissAir";
            fp.InitialLocation           = new Location();
            fp.InitialLocation.Longitude = 35;
            fp.InitialLocation.Latitude  = 32;
            fp.InitialLocation.DateTime  = DateTime.UtcNow;
            fp.Segments = new List <Segment>();
            Segment seg = new Segment();

            seg.Longitude       = 36;
            seg.Latitude        = 33;
            seg.TimespanSeconds = 650;
            fp.Segments.Add(seg);
            // Post the preapared flightPlan.
            ActionResult resp = fpController.Post(fp);
            ObjectResult res  = resp as ObjectResult;

            // Check the status code of the response and check it equals
            // to the flight plan which was sent.
            Assert.AreEqual(res.StatusCode, 201);
            Assert.AreEqual(res.Value, fp);
            var iter = fpController.HttpContext.Response.Headers.Values.GetEnumerator();

            iter.MoveNext();
            // Get the interal flight id.
            string internalFlightId = iter.Current.ToArray()[0];

            // Check Post method of servers.
            ServersController serverController = new ServersController(cache);
            Server            testServer       = new Server();

            testServer.Id  = "test";
            testServer.Url = "http://www.testServer.com/";
            // Post the prepared server.
            resp = serverController.Post(testServer);
            res  = resp as ObjectResult;
            // Check the status code of the response and check it equals
            // to the server which was sent.
            Assert.AreEqual(res.StatusCode, 201);
            Assert.AreEqual(res.Value, testServer);

            // Inject fake MessegeHandler to HttpClient.
            // Create new HttpClient and override it's response method with a stub one.
            HttpClient client = new HttpClient(new HttpMessageHandlerStub());
            // Check get method of flights.
            FlightsController flightController = new FlightsController(cache, client)
            {
                ControllerContext = new ControllerContext
                {
                    HttpContext = new DefaultHttpContext()
                }
            };

            // Add sync_all to query.
            flightController.HttpContext.Request.QueryString = new QueryString("?sync_all");
            Task <ActionResult <List <Flight> > > respFlights = flightController.Get(DateTime.UtcNow);

            res = respFlights.Result.Result as ObjectResult;
            Assert.AreEqual(res.StatusCode, 200);
            // Check that we get two flights-
            // the first one is the one was sent earlier in this test.
            // the second one is a fake external flight which was generated by the stub.
            Assert.AreEqual(((List <Flight>)res.Value).Count, 2);
            Flight internalFlight = ((List <Flight>)res.Value)[0];
            Flight externalFlight = ((List <Flight>)res.Value)[1];

            Assert.AreEqual(internalFlight.FlightId, internalFlightId);
            Assert.AreEqual(internalFlight.IsExternal, false);
            Assert.AreEqual(externalFlight.FlightId, "FP00000000");
            Assert.AreEqual(externalFlight.IsExternal, true);
        }
예제 #15
0
 /// <summary>
 /// 设置缓存的值
 /// </summary>
 /// <param name="key">关键字</param>
 /// <param name="value">值</param>
 public void Set(string key, object value)
 {
     memoryCache.Set(key, value);
 }
예제 #16
0
 public void CacheCallResult(object result, string argument, double _cacheRetainSeconds)
 {
     _cache.Set(argument, result, DateTimeOffset.Now.AddSeconds(_cacheRetainSeconds));
 }
예제 #17
0
        public async Task ProcessAsync_FlowsEntryLinkThatAllowsAddingTriggersToAddedEntry()
        {
            // Arrange
            var id = "some-id";
            var expectedContent = new DefaultTagHelperContent();
            expectedContent.SetContent("some-content");
            var tokenSource = new CancellationTokenSource();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .AddExpirationToken(new CancellationChangeToken(tokenSource.Token));
            var tagHelperContext = new TagHelperContext(
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary<object, object>(),
                uniqueId: id);
            var tagHelperOutput = new TagHelperOutput(
                "cache",
                new TagHelperAttributeList { { "attr", "value" } },
                getChildContentAsync: useCachedResult =>
                {
                    TagHelperContent tagHelperContent;
                    if (!cache.TryGetValue("key1", out tagHelperContent))
                    {
                        tagHelperContent = expectedContent;
                        cache.Set("key1", tagHelperContent, cacheEntryOptions);
                    }

                    return Task.FromResult(tagHelperContent);
                });
            tagHelperOutput.PreContent.SetContent("<cache>");
            tagHelperOutput.PostContent.SetContent("</cache>");
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ViewContext = GetViewContext(),
            };
            var key = cacheTagHelper.GenerateKey(tagHelperContext);

            // Act - 1
            await cacheTagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);
            IHtmlContent cachedValue;
            var result = cache.TryGetValue(key, out cachedValue);

            // Assert - 1
            Assert.Equal("HtmlEncode[[some-content]]", tagHelperOutput.Content.GetContent());
            Assert.True(result);

            // Act - 2
            tokenSource.Cancel();
            result = cache.TryGetValue(key, out cachedValue);

            // Assert - 2
            Assert.False(result);
            Assert.Null(cachedValue);
        }
        public void OvercapacityPurge_AreThreadSafe()
        {
            var cache = new MemoryCache(new MemoryCacheOptions
            {
                ExpirationScanFrequency = TimeSpan.Zero,
                SizeLimit            = 10,
                CompactionPercentage = 0.5
            });
            var cts           = new CancellationTokenSource();
            var limitExceeded = false;

            var task0 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (cache.Size > 10)
                    {
                        limitExceeded = true;
                        break;
                    }
                    cache.Set(Guid.NewGuid(), Guid.NewGuid(), new MemoryCacheEntryOptions {
                        Size = 1
                    });
                }
            }, cts.Token);

            var task1 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (cache.Size > 10)
                    {
                        limitExceeded = true;
                        break;
                    }
                    cache.Set(Guid.NewGuid(), Guid.NewGuid(), new MemoryCacheEntryOptions {
                        Size = 1
                    });
                }
            }, cts.Token);

            var task2 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (cache.Size > 10)
                    {
                        limitExceeded = true;
                        break;
                    }
                    cache.Set(Guid.NewGuid(), Guid.NewGuid(), new MemoryCacheEntryOptions {
                        Size = 1
                    });
                }
            }, cts.Token);

            cts.CancelAfter(TimeSpan.FromSeconds(5));
            var task3 = Task.Delay(TimeSpan.FromSeconds(7));

            Task.WaitAll(task0, task1, task2, task3);

            Assert.Equal(TaskStatus.RanToCompletion, task0.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task1.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task2.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task3.Status);
            Assert.Equal(cache.Count, cache.Size);
            Assert.InRange(cache.Count, 0, 10);
            Assert.False(limitExceeded);
        }
        public void AddAndReplaceEntries_AreThreadSafe()
        {
            var cache = new MemoryCache(new MemoryCacheOptions
            {
                ExpirationScanFrequency = TimeSpan.Zero,
                SizeLimit            = 20,
                CompactionPercentage = 0.5
            });
            var cts = new CancellationTokenSource();

            var random = new Random();

            var task0 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    var entrySize = random.Next(0, 5);
                    cache.Set(random.Next(0, 10), entrySize, new MemoryCacheEntryOptions {
                        Size = entrySize
                    });
                }
            });

            var task1 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    var entrySize = random.Next(0, 5);
                    cache.Set(random.Next(0, 10), entrySize, new MemoryCacheEntryOptions {
                        Size = entrySize
                    });
                }
            });

            var task2 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    var entrySize = random.Next(0, 5);
                    cache.Set(random.Next(0, 10), entrySize, new MemoryCacheEntryOptions {
                        Size = entrySize
                    });
                }
            });

            cts.CancelAfter(TimeSpan.FromSeconds(5));
            var task3 = Task.Delay(TimeSpan.FromSeconds(7));

            Task.WaitAll(task0, task1, task2, task3);

            Assert.Equal(TaskStatus.RanToCompletion, task0.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task1.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task2.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task3.Status);

            var cacheSize = 0;

            for (var i = 0; i < 10; i++)
            {
                cacheSize += cache.Get <int>(i);
            }

            Assert.Equal(cacheSize, cache.Size);
            Assert.InRange(cache.Count, 0, 20);
        }
예제 #20
0
        public void ReturnsValueFromCache()
        {
            // Arrange
            var filePath = "/hello/world";
            var fileProvider = GetMockFileProvider(filePath);
            var memoryCache = new MemoryCache(new MemoryCacheOptions());
            memoryCache.Set(filePath, "FromCache");
            var fileVersionProvider = new FileVersionProvider(
                fileProvider,
                memoryCache,
                GetRequestPathBase());

            // Act
            var result = fileVersionProvider.AddFileVersionToPath(filePath);

            // Assert
            Assert.Equal("FromCache", result);
        }
예제 #21
0
        public void Main()
        {
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            object result;
            string key = "Key";
            object newObject = new object();
            object state = new object();

            // Basic CRUD operations:

            // Create / Overwrite
            result = cache.Set(key, newObject);
            result = cache.Set(key, new object());

            // Retrieve, null if not found
            result = cache.Get(key);

            // Retrieve
            bool found = cache.TryGetValue(key, out result);

            // Delete
            cache.Remove(key);

            // Cache entry configuration:

            // Stays in the cache as long as possible
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove));

            // Automatically remove if not accessed in the given time
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5)));

            // Automatically remove at a certain time
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2)));

            // Automatically remove at a certain time, which is relative to UTC now
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions().SetAbsoluteExpiration(relative: TimeSpan.FromMinutes(10)));

            // Automatically remove if not accessed in the given time
            // Automatically remove at a certain time (if it lives that long)
            result = cache.Set(
                key,
                new object(),
                new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromMinutes(5))
                .SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddDays(2)));

            // Callback when evicted
            var options = new MemoryCacheEntryOptions()
                .RegisterPostEvictionCallback(
                (echoKey, value, reason, substate) =>
                {
                    Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                });
            result = cache.Set(key, new object(), options);

            // Remove on token expiration
            var cts = new CancellationTokenSource();
            options = new MemoryCacheEntryOptions()
                .AddExpirationToken(new CancellationChangeToken(cts.Token))
                .RegisterPostEvictionCallback(
                (echoKey, value, reason, substate) =>
                {
                    Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                });
            result = cache.Set(key, new object(), options);

            // Fire the token to see the registered callback being invoked
            cts.Cancel();

            // Expire an entry if the dependent entry expires
            using (var link = cache.CreateLinkingScope())
            {
                cts = new CancellationTokenSource();
                cache.Set("key1", "value1", new MemoryCacheEntryOptions()
                    .AddExpirationToken(new CancellationChangeToken(cts.Token)));

                // expire this entry if the entry with key "key1" expires.
                cache.Set("key2", "value2", new MemoryCacheEntryOptions()
                    .AddEntryLink(link)
                    .RegisterPostEvictionCallback(
                    (echoKey, value, reason, substate) =>
                    {
                        Console.WriteLine(echoKey + ": '" + value + "' was evicted due to " + reason);
                    }));
            }

            // Fire the token to see the registered callback being invoked
            cts.Cancel();
        }