/// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存Key</param> /// <returns></returns> public static T Get <T>(string key) where T : class { if (key == null) { throw new ArgumentNullException(nameof(key)); } return(Cache.Get(key) as T); }
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); }
protected override Task <T> GetAsync <T>( CacheKey cacheKey, CancellationToken cancellationToken) { var value = _memoryCache.Get(cacheKey.Value) as T; return(Task.FromResult(value)); }
public T GetHash <T>(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)) { return((T)dicts[field]); } return(default(T)); }
/// <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); }
public object GetValue(string key) { return(_memoryCache.Get(key)); }
public object GetCachedResult(string argument) { return(_cache.Get(argument)); }
public override object GetOrDefault(string key) { return(_memoryCache.Get(key)); }
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); }
/// <summary> /// 获取缓存的数据 /// </summary> /// <param name="key">关键字</param> /// <returns></returns> public object Get(string key) { return(memoryCache.Get(key)); }
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(); }