Asp.NetCore CacheHelper汎用キャッシュヘルプクラス
12862 ワード
using System;
using Microsoft.Extensions.Caching.Memory;
using System.Runtime;
namespace UFX.Tools
{
public class CacheHelper
{
public static IMemoryCache _memoryCache= new MemoryCache(new MemoryCacheOptions());
/// <summary>
///
/// </summary>
///<param name="key">Cache </param>
///<param name="value"> Cache[key] </param>
///<param name="minute">minute </param>
public static void CacheInsertAddMinutes(string key, object value, int minute)
{
if (value == null) return;
_memoryCache.Set(key, value, new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(minute)));
}
/// <summary>
/// , minute
/// </summary>
///<param name="key">Cache </param>
///<param name="value"> Cache[key] </param>
///<param name="minute"> </param>
public static void CacheInsertFromMinutes(string key, object value, int minute)
{
if (value == null) return;
_memoryCache.Set(key, value, new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(minute)));
}
/// <summary>
/// key , value Cache[key]. , .
/// </summary>
///<param name="key">Cache </param>
///<param name="value"> Cache[key] </param>
public static void CacheInsert(string key, object value)
{
_memoryCache.Set(key, value);
}
/// <summary>
/// Cache[key]
/// </summary>
///<param name="key"></param>
public static void CacheNull(string key)
{
_memoryCache.Remove(key);
}
/// <summary>
/// key , Cache[key]
/// </summary>
///<param name="key"></param>
public static object CacheValue(string key)
{
return _memoryCache.Get(key);
}
#region
//public IActionResult Index()
//{
// string cacheKey = "key";
// string result;
// if (!_memoryCache.TryGetValue(cacheKey, out result))
// {
// result = $"LineZero{DateTime.Now}";
// _memoryCache.Set(cacheKey, result);
// // 2
// _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
// .SetSlidingExpiration(TimeSpan.FromMinutes(2)));
// // 2
// _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
// .SetAbsoluteExpiration(TimeSpan.FromMinutes(2)));
// //
// _memoryCache.Remove(cacheKey);
// // ( , )
// _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
// .SetPriority(CacheItemPriority.NeverRemove));
// // 10
// _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
// .SetAbsoluteExpiration(TimeSpan.FromSeconds(10))
// .RegisterPostEvictionCallback((key, value, reason, substate) =>
// {
// Console.WriteLine($" {key} {value} , {reason}");
// }));
// // Token
// var cts = new CancellationTokenSource();
// _memoryCache.Set(cacheKey, result, new MemoryCacheEntryOptions()
// .AddExpirationToken(new CancellationChangeToken(cts.Token))
// .RegisterPostEvictionCallback((key, value, reason, substate) =>
// {
// Console.WriteLine($" {key} {value} , {reason}");
// }));
// cts.Cancel();
// }
// ViewBag.Cache = result;
// return View();
//}
#endregion
}
}
先にダウンロードすることを忘れないでください:Microsoft.Extensions.Caching.Memory;