Files
simapi-net/Helpers/SimApiCache.cs
T

68 lines
1.6 KiB
C#
Raw Normal View History

2025-01-16 22:05:59 +08:00
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
namespace SimApi.Helpers;
public class SimApiCache(IDistributedCache cache)
{
2025-05-14 06:26:10 +08:00
private const string Prefix = "SimApi:Cache:";
2025-01-16 22:05:59 +08:00
2026-04-26 10:03:38 +08:00
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="options"></param>
2025-01-16 22:05:59 +08:00
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
{
if (options is not null)
{
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
}
else
{
cache.SetString(Prefix + key, SimApiUtil.Json(value));
}
}
2026-04-26 10:03:38 +08:00
/// <summary>
/// 移除缓存
/// </summary>
/// <param name="key"></param>
2026-04-26 01:23:14 +08:00
public void Remove(string key)
{
cache.Remove(Prefix + key);
}
2026-04-26 18:43:34 +08:00
/// <summary>
/// 缓存Key是否存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool HasKey(string key)
{
return Get<string>(key) != null;
}
2026-04-26 10:03:38 +08:00
/// <summary>
/// 获取string类型缓存
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
2025-01-16 22:05:59 +08:00
public string? Get(string key)
{
return cache.GetString(Prefix + key);
}
2026-04-26 10:03:38 +08:00
/// <summary>
/// 获取特定类型缓存
/// </summary>
/// <param name="key"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
2025-01-16 22:05:59 +08:00
public T? Get<T>(string key)
{
var data = cache.GetString(Prefix + key);
return data == null ? default : JsonSerializer.Deserialize<T>(data);
}
}