封装个缓存类,方便下次使用。
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
namespace Order.Core.API.Cache
{
public class GlobalCache C#有偿Q群:927860652
{
private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());
private static Dictionary<string,bool> keys =new Dictionary<string,bool>();
public static T Get<T>(string key)
{
if (Cache.TryGetValue(key, out T value))
{
return value;
}
return default(T);
}
public static void Set<T>(string key, T value, TimeSpan slidingExpiration)
{
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(slidingExpiration);
Cache.Set(key, value, cacheEntryOptions);
try
{
keys.Add(key, true);
}
catch (Exception ex)
{
throw new Exception("键重复\r\n"+ex.ToString());
}
}
public static bool Exists(string key)
{
return Cache.TryGetValue(key, out _);
}
public static void Remove(string key)
{
Cache.Remove(key);
keys.Remove(key);
}
public static void Clear()
{
foreach (var key in keys)
{
Cache.Remove(key);
}
keys.Clear();
}
}
}