using System;
using System.Text;
using Masuit.Tools.Systems;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
namespace Masuit.Tools.AspNetCore.Extensions;
///
///
///
public static class DistributedCacheExt
{
public static T GetOrAdd(this IDistributedCache cache, string key, Func valueFactory)
{
var bytes = cache.Get(key);
if (bytes is null)
{
var value = new NullObject(valueFactory());
bytes = Encoding.UTF8.GetBytes(value.ToJsonString());
cache.Set(key, bytes);
return value;
}
return JsonConvert.DeserializeObject>(Encoding.UTF8.GetString(bytes));
}
public static T Get(this IDistributedCache cache, string key)
{
var bytes = cache.Get(key);
if (bytes is null)
{
return default;
}
return JsonConvert.DeserializeObject>(Encoding.UTF8.GetString(bytes));
}
public static void Set(this IDistributedCache cache, string key, T value)
{
cache.Set(key, Encoding.UTF8.GetBytes(new NullObject(value).ToJsonString()), new DistributedCacheEntryOptions());
}
public static void Set(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options)
{
cache.Set(key, Encoding.UTF8.GetBytes(new NullObject(value).ToJsonString()), options);
}
public static T GetOrAdd(this IDistributedCache cache, string key, T value)
{
var bytes = cache.Get(key);
if (bytes is null)
{
bytes = Encoding.UTF8.GetBytes(new NullObject(value).ToJsonString());
cache.Set(key, bytes);
return value;
}
return JsonConvert.DeserializeObject>(Encoding.UTF8.GetString(bytes));
}
public static void AddOrUpdate(this IDistributedCache cache, string key, T addValue, Func updateFunc)
{
var bytes = cache.Get(key);
if (bytes is null)
{
bytes = Encoding.UTF8.GetBytes(new NullObject(addValue).ToJsonString());
cache.Set(key, bytes);
return;
}
var value = new NullObject(updateFunc(JsonConvert.DeserializeObject>(Encoding.UTF8.GetString(bytes))));
cache.Set(key, Encoding.UTF8.GetBytes(value.ToJsonString()));
}
}