namespace ConsoleCache
{
public class CustomCache
{
static CustomCache()
{
//定时删除
Task.Run(() =>
{
while (true)//死循环
{
List<string> keyList = new List<string>();
foreach (var key in CustomCacheDictionary.Keys)
{
if (DateTime.Now > CustomCacheDictionary[key].Value)
{
keyList.Add(key);
}
}
keyList.ForEach(k => CustomCacheDictionary.Remove(k));
}
});
}
private static Dictionary<string, KeyValuePair<object,DateTime>> CustomCacheDictionary = new Dictionary<string, KeyValuePair<object, DateTime>>();
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key"></param>
/// <param name="ovalue"></param>
/// <param name="timeoutSecond"></param>
public static void Save(string key, object ovalue,int timeoutSecond=1800)
{
CustomCacheDictionary.Add(key, new KeyValuePair<object, DateTime>(ovalue, DateTime.Now.AddSeconds(timeoutSecond)));
}
/// <summary>
/// 获取
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetT<T>(string key)
{
return (T)CustomCacheDictionary[key].Key;
}
/// <summary>
/// 检查时候存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Exist(string key)
{
if (CustomCacheDictionary.ContainsKey(key))
{
var valueTime = CustomCacheDictionary[key];
if (DateTime.Now > valueTime.Value)
{
CustomCacheDictionary.Remove(key);
return false;
}
else
{
return true;
}
}
return false;
}
/// <summary>
/// 删除所有
/// </summary>
public static void RemoveAll()
{
CustomCacheDictionary.Clear();
}
/// <summary>
/// 选择性删除
/// </summary>
/// <param name="func"></param>
public static void RemoveCondition(Func<string,bool> func)
{
List<string> keyList = new List<string>();
foreach (var key in CustomCacheDictionary.Keys)
{
if (func.Invoke(key))
{
keyList.Add(key);
}
}
keyList.ForEach(k => CustomCacheDictionary.Remove(k));
}
/// <summary>
/// 封装获取写入缓存并获取缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="func"></param>
/// <returns></returns>
public static T GetData<T>(string key, Func<T> func)
{
T tResult = default(T);
if (!CustomCache.Exist(key))
{
tResult = func.Invoke();
CustomCache.Save(key,tResult);
}
else
{
tResult = CustomCache.GetT<T>(key);
}
return tResult;
}
}
}
namespace ConsoleCache
{
/// <summary>
/// 缓存字典
/// </summary>
class Program
{
static void Main(string[] args)
{
//string name = $"{nameof(CustomCache.GetData)}_1";
//for (int i = 0; i < 4; i++)
//{
// int Result = CustomCache.GetData<int>(name, () => DataSource.QueryByDB(123));
// Console.WriteLine(Result);
//}
CustomCache.Save("123_favorite_category_", new List<string>() { "编程语言", "移动开发" });
CustomCache.Save("456_favorite_category_", new List<string>() { "编程语言", "移动开发", "平面设计" });
CustomCache.Save("123_favorite_", new List<string>() { "编程语言", });
CustomCache.RemoveCondition(s => s.Contains("_category_"));
}
}
}