using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
namespace SimApi.Helpers;
public class SimApiCache(IDistributedCache cache)
{
private const string Prefix = "SimApi:Cache:";
///
/// 设置缓存 (值不能为null)
///
///
///
///
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
{
SimApiError.ErrorWhenNull(value, 400, "缓存值不能为null");
if (options is not null)
{
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
}
else
{
cache.SetString(Prefix + key, SimApiUtil.Json(value));
}
}
///
/// 移除缓存
///
///
public void Remove(string key)
{
cache.Remove(Prefix + key);
}
///
/// 缓存Key是否存在
///
///
///
public bool HasKey(string key)
{
return Get(key) != null;
}
///
/// 获取string类型缓存
///
///
///
public string? Get(string key)
{
return Get(Prefix + key);
}
///
/// 获取特定类型缓存
///
///
///
///
public T? Get(string key)
{
var data = cache.GetString(Prefix + key);
return data == null ? default : SimApiUtil.FromJson(data);
}
}